Solving Leetcode Interviews in Seconds with AI: Contiguous Array
Introduction
In this blog post, we will explore how to solve the LeetCode problem "525" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1. Example 1: Input: nums = [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1. Example 2: Input: nums = [0,1,0] Output: 2 Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. Example 3: Input: nums = [0,1,1,1,1,1,0,0,0] Output: 6 Explanation: [1,1,1,0,0,0] is the longest contiguous subarray with equal number of 0 and 1. Constraints: 1 <= nums.length <= 105 nums[i] is either 0 or 1.
Explanation
Here's a breakdown of the approach, followed by the Python code:
- Key Idea: Transform the problem into finding the longest subarray with a sum of zero. Replace all 0s with -1s. A subarray with an equal number of 0s and 1s will then have a sum of zero.
- Prefix Sum & Hash Map: Calculate the prefix sum as we iterate through the modified array. Store the prefix sum and its index in a hash map. If we encounter the same prefix sum again, it means the subarray between the previous index and the current index has a sum of zero.
Maximize Length: Track the maximum length of the subarray encountered with a sum of zero.
Runtime Complexity: O(n), Storage Complexity: O(n)
Code
def findMaxLength(nums: list[int]) -> int:
"""
Finds the maximum length of a contiguous subarray with an equal number of 0 and 1.
"""
max_length = 0
count = 0 # Prefix sum (1 counts as +1, 0 counts as -1)
prefix_sum_map = {0: -1} # Initialize with count 0 at index -1
for i, num in enumerate(nums):
if num == 0:
count -= 1
else:
count += 1
if count in prefix_sum_map:
max_length = max(max_length, i - prefix_sum_map[count])
else:
prefix_sum_map[count] = i
return max_length