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 <= 105nums[i] is either 0 or 1.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are given a mixed line of two different colored items and you need to find the longest continuous section that has an equal number of both colors. The brute force approach simply investigates every single possible starting point and every possible ending point to check every possible section.
Here's how the algorithm would work step-by-step:
def find_max_length(binary_array):
max_length_found = 0
# Iterate through every possible starting position in the array
for start_position in range(len(binary_array)):
zeros_count = 0
ones_count = 0
# Iterate through every possible ending position starting from the chosen start
for end_position in range(start_position, len(binary_array)):
if binary_array[end_position] == 0:
zeros_count += 1
else:
ones_count += 1
# Check if the current section contains an equal number of both items
if zeros_count == ones_count:
current_length = (end_position - start_position) + 1
if current_length > max_length_found:
max_length_found = current_length
return max_length_foundInstead of checking every possible grouping of items, the optimal strategy keeps a running score as you walk down the line, treating one type of item as positive and the other as negative. By remembering the exact moments you have seen specific scores before, you can instantly find the longest stretch where the score balances out to zero.
Here's how the algorithm would work step-by-step:
def find_max_length(binary_array):
running_score = 0
max_length = 0
score_to_index_map = {0: -1}
# Pre-populating the hash map with score zero at index negative one allows us to correctly calculate lengths of subarrays that start from the very beginning of the input array.
for current_index, current_element in enumerate(binary_array):
if current_element == 1:
running_score += 1
else:
running_score -= 1
# If we have seen this running score before, the subarray between the previous occurrence and the current index has a net change of zero, meaning 0s and 1s are balanced.
if running_score in score_to_index_map:
previous_index = score_to_index_map[running_score]
current_length = current_index - previous_index
if current_length > max_length:
max_length = current_length
else:
score_to_index_map[running_score] = current_index
# Returning the maximum length found ensures we output the longest contiguous subarray with an equal number of 0s and 1s.
return max_length| Case | How to Handle |
|---|---|
| Empty array or single element array | Return zero immediately since a balanced subarray requires at least two elements. |
| Array with all zeros or all ones | The prefix sum never repeats except at the initial sentinel value, resulting in a maximum length of zero. |
| Alternating ones and zeros starting with either value | Prefix sums will fluctuate and return to previous values frequently, correctly capturing the entire array as the maximum length. |
| No valid balanced subarray exists in the entire array | The maximum length variable remains initialized at zero and is returned as the final result. |
| Multiple identical prefix sum values appearing at different indices | Store only the earliest occurrence of each prefix sum in the hash map to maximize the calculated subarray length. |
| Very large arrays with millions of elements | The O(n) linear scan with a hash map ensures efficient time complexity and prevents timeout errors. |
| Extremely skewed distributions like 99 percent ones and 1 percent zeros | The algorithm still processes each element in a single pass maintaining optimal O(n) time performance. |
| Prefix sum counter values exceeding standard integer limits | Using standard 32-bit signed integers is sufficient because the sum increments or decrements by at most one per element. |