Taro Logo

Contiguous Array

#207 Most AskedMedium
0 views
Topics:
Arrays

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.

Solution


Clarifying Questions

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:

  1. What should be returned if the input array is empty or null, and can we expect any elements other than 0 and 1?
  2. Are we guaranteed that the input array contains only binary values (0s and 1s), or do I need to validate the input for other integers?
  3. If multiple subarrays of the same maximum length exist with an equal number of 0s and 1s, does it matter which one's length we return?
  4. Should I return the actual maximum length as an integer, or do I need to return the starting and ending indices of the subarray?
  5. Is the term "contiguous subarray" strictly referring to a sequence of elements occupying consecutive positions in the original array?

Brute Force Solution

Approach

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:

  1. Pick a starting position near the very beginning of the line.
  2. Look at every possible ending position that comes after your chosen starting position, moving one step at a time.
  3. For every section you carve out between your start and end positions, count how many items of the first color and how many items of the second color are inside.
  4. If the counts of both colors happen to be exactly equal, measure how long this section is.
  5. Keep a mental note of the length every time you find a section with an equal number of both colors.
  6. Shift your starting position one spot to the right and repeat the entire process of checking every ending position again.
  7. Once you have tested every possible start and end combination, look back at your mental notes and identify the largest measured length.

Code Implementation

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_found

Big(O) Analysis

Time Complexity
O(n²) – The brute force approach uses a nested loop structure where the outer loop picks each of the n possible starting positions in the array. For every starting position, the inner loop explores every possible ending position that follows it, checking all subarrays. As the outer loop advances, the inner loop examines (n-1) elements, then (n-2) elements, and so on. This nested iteration results in approximately n * n/2 total operations, which simplifies to a quadratic time complexity of O(n²).
Space Complexity
O(1) – To determine the auxiliary space complexity for this brute force approach, we look at the variables used to track the starting position, ending position, and the counts of each color. These variables use a constant amount of extra memory regardless of the input size. Since no additional data structures like hash maps or temporary lists are created to store intermediate results, the memory usage remains completely flat. Therefore, as the input size N grows, the extra auxiliary memory required stays constant, resulting in O(1) space complexity.

Optimal Solution

Approach

Instead 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:

  1. Imagine walking down a row of items, where you assign a value of positive one to the first type of item and negative one to the second type.
  2. Keep a running total of your score as you examine each item, starting your journey at a baseline score of zero.
  3. Make a mental note of every time you reach a specific score for the very first time, along with how many steps you have taken to get there.
  4. If you encounter a score that you have already seen earlier in your journey, it means all the items you passed between that earlier moment and right now have perfectly balanced each other out.
  5. Whenever you find a repeat score, calculate the distance between your current position and the very first time you recorded that score.
  6. Keep track of the longest distance you discover where the scores balance out.
  7. Continue this process until you reach the end of the items, and your longest recorded distance will be your final answer.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n) – As we walk down the row of n items, we examine each item exactly once in a single linear pass. During this journey, performing the running total update and checking or updating our recorded scores in a hash map takes constant time on average per item. This means the total operations grow linearly with the input size n, which simplifies directly to O(n).
Space Complexity
O(n) – The auxiliary space is driven by a hash map used to store each unique running score encountered and the earliest index at which it appeared. As we iterate through the input array of size N, we may record up to N distinct running scores in this hash map. Therefore, the memory consumed by the hash map scales directly with the length of the input. Concluding the analysis, the total extra memory simplifies to Big O of n.

Edge Cases

Empty array or single element array
How to Handle:
Return zero immediately since a balanced subarray requires at least two elements.
Array with all zeros or all ones
How to Handle:
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
How to Handle:
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
How to Handle:
The maximum length variable remains initialized at zero and is returned as the final result.
Multiple identical prefix sum values appearing at different indices
How to Handle:
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
How to Handle:
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
How to Handle:
The algorithm still processes each element in a single pass maintaining optimal O(n) time performance.
Prefix sum counter values exceeding standard integer limits
How to Handle:
Using standard 32-bit signed integers is sufficient because the sum increments or decrements by at most one per element.
0/257 completed