Bird
Raised Fist0
Interview Prepknowing-what-to-trackmediumAmazonGoogle

Subarray with Equal Number of 0s and 1s

Choose your preparation mode4 modes available
📋
Problem

Imagine analyzing a binary signal to find the longest balanced segment where zeros and ones appear equally, crucial for error detection in communication systems.

Given a binary array nums, find the length of the longest contiguous subarray with an equal number of 0s and 1s. Return the length of such a subarray.

1 ≤ nums.length ≤ 10^5nums[i] is either 0 or 1
Edge cases: All zeros → output 0 (no equal subarray)All ones → output 0 (no equal subarray)Single element array → output 0 (cannot have equal 0s and 1s)
</>
IDE
def findMaxLength(nums: list[int]) -> int:public int findMaxLength(int[] nums)int findMaxLength(vector<int>& nums)function findMaxLength(nums)
def findMaxLength(nums):
    # Write your solution here
    pass
class Solution {
    public int findMaxLength(int[] nums) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int findMaxLength(vector<int>& nums) {
    // Write your solution here
    return 0;
}
function findMaxLength(nums) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: 0Always returning 0 due to missing prefix sum tracking or never updating max length.✅ Initialize hash map with sum 0 at index -1 and update max length when prefix sum repeats.
Wrong: length of first balanced subarray found instead of longestGreedy approach that stops at first balanced subarray.✅ Continue scanning entire array and update max length whenever prefix sum repeats at a later index.
Wrong: Incorrect length due to treating 0 and 1 as separate counts without prefix sum conversionNot converting 0 to -1, causing incorrect running sum calculations.✅ Convert 0 to -1 before computing prefix sums to track balance correctly.
Wrong: Crashes or errors on empty inputNo check for empty array before processing.✅ Add base case to return 0 if input array is empty.
Wrong: Timeout on large inputsUsing O(n^2) brute force approach.✅ Implement O(n) prefix sum with hash map approach to pass performance tests.
✓
Test Cases
t1_01basic
Input{"nums":[0,1]}
Expected2

The entire array has equal number of 0s and 1s.

t1_02basic
Input{"nums":[0,1,0,1,1,1,0]}
Expected4

Longest balanced subarray is [0,1,0,1] with length 4.

t2_01edge
Input{"nums":[]}
Expected0

Empty array has no subarrays, so result is 0.

t2_02edge
Input{"nums":[0]}
Expected0

Single element cannot have equal number of 0s and 1s.

t2_03edge
Input{"nums":[0,0,0,0]}
Expected0

All zeros means no subarray with equal 0s and 1s.

t3_01corner
Input{"nums":[0,1,1,0,1,1,1,0,0]}
Expected6

Longest balanced subarray is [1,0,1,1,1,0,0] partial balanced segment is [1,0,1,1,1,0,0] but max balanced is [1,0,1,1] or [0,1,1,0] length 4.

t3_02corner
Input{"nums":[0,0,1,1,0,1,0,1,1,0]}
Expected10

Entire array is balanced with equal number of 0s and 1s.

t3_03corner
Input{"nums":[1,1,1,0,0,0,1,0]}
Expected8

Entire array is balanced with equal number of 0s and 1s.

t4_01performance
Input{"nums":[0,1,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0]}
⏱ Performance - must finish in 2000ms

Input size n=100 with alternating 0 and 1; O(n) solution must complete within 2 seconds.

Practice

(1/5)
1. Given the following Python code implementing the optimal approach for longest consecutive sequence, what is the value of max_len returned when the input is [1, 9, 3, 10, 4, 20, 2]?
def longestConsecutive(nums):
    num_set = set(nums)
    max_len = 0
    for num in num_set:
        if num - 1 not in num_set:
            current = num
            length = 1
            while current + 1 in num_set:
                current += 1
                length += 1
            max_len = max(max_len, length)
    return max_len
easy
A. 5
B. 4
C. 3
D. 2

Solution

  1. Step 1: Identify sequence starts

    Numbers without predecessor: 1 (0 not in set), 9 (8 not in set), 20 (19 not in set).
  2. Step 2: Trace sequences from starts

    From 1: sequence is 1,2,3,4 -> length 4; from 9: 9,10 -> length 2; from 20: 20 -> length 1. Max length is 4.
  3. Step 3: Re-examine carefully

    Check if 1,2,3,4 is the longest. Actually, 1,2,3,4 is length 4, but 1,2,3,4,5 is not present. So max length is 4.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Longest consecutive sequence length is 4 [OK]
Hint: Only count sequences starting at numbers without predecessor [OK]
Common Mistakes:
  • Counting sequences from every number
  • Off-by-one in length calculation
  • Ignoring duplicates
2. Consider the following code snippet implementing the optimal prefix sum with hash map approach. What is the final returned value when the input is nums = [1, 2, 3] and k = 3?
def subarraySum(nums, k):
    count = 0
    running_sum = 0
    prefix_counts = {0: 1}
    for num in nums:
        running_sum += num
        if running_sum - k in prefix_counts:
            count += prefix_counts[running_sum - k]
        prefix_counts[running_sum] = prefix_counts.get(running_sum, 0) + 1
    return count

print(subarraySum([1, 2, 3], 3))
easy
A. 3
B. 0
C. 1
D. 2

Solution

  1. Step 1: Trace running_sum and prefix_counts

    Iteration 1: running_sum=1, prefix_counts={0:1,1:1}, count=0 Iteration 2: running_sum=3, running_sum-k=0 in prefix_counts, count=1, prefix_counts={0:1,1:1,3:1} Iteration 3: running_sum=6, running_sum-k=3 in prefix_counts, count=2, prefix_counts={0:1,1:1,3:1,6:1}
  2. Step 2: Return count

    Count is 2, representing subarrays [1,2] and [3].
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Count matches expected subarrays summing to 3. [OK]
Hint: Track running_sum and prefix_counts carefully [OK]
Common Mistakes:
  • Off-by-one errors in counting
  • Forgetting to initialize prefix_counts with {0:1}
  • Miscounting subarrays ending at current index
3. The following code attempts to find the longest contiguous subarray with equal 0s and 1s. Which line contains a subtle bug that causes incorrect results on some inputs?
medium
A. Line 6: Initializing seen as empty dictionary instead of {0: -1}
B. Line 5: Initializing max_length to 0
C. Line 4: Initializing prefix_sum to 0
D. Line 8: Updating max_length with max of current and new length

Solution

  1. Step 1: Understand the role of seen dictionary initialization

    Seen must map prefix_sum 0 to index -1 to handle subarrays starting at index 0.
  2. Step 2: Identify that initializing seen as empty misses subarrays starting at index 0

    Without {0: -1}, the code misses valid subarrays from the start, causing off-by-one errors.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Other lines are correct; only seen initialization causes subtle bugs [OK]
Hint: Always initialize seen with {0: -1} for prefix sums [OK]
Common Mistakes:
  • Not initializing seen with 0:-1
  • Overwriting earliest prefix sum indices
  • Not transforming 0 to -1
4. The following code attempts to find the pivot index but contains a subtle bug. Which line contains the bug?
def pivotIndex(nums):
    total = sum(nums)
    left_sum = 0
    for i, num in enumerate(nums):
        if left_sum == total - left_sum:
            return i
        left_sum += num
    return -1
medium
A. Line 6: left_sum += num
B. Line 4: for i, num in enumerate(nums):
C. Line 2: total = sum(nums)
D. Line 5: if left_sum == total - left_sum:

Solution

  1. Step 1: Understand the condition

    The condition should check if left_sum equals right sum, which is total - left_sum - current num.
  2. Step 2: Identify the bug

    The code incorrectly checks if left_sum == total - left_sum, missing subtracting the current num, causing wrong pivot detection.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Correct condition is left_sum == total - left_sum - num [OK]
Hint: Check if right sum calculation includes current element [OK]
Common Mistakes:
  • Forgetting to subtract current num from total
  • Misplacing sum updates
  • Returning null instead of -1
5. Suppose the input array can contain negative numbers and you want to find the number of subarrays whose sum equals k, but now you want to find the count of subarrays with sum divisible by k instead. Which modification to the optimal prefix sum with hash map approach correctly solves this variant?
hard
A. Use a sliding window approach since divisibility allows shrinking the window easily.
B. Track prefix sums modulo k and count frequencies of each remainder in a hash map.
C. Sort the array and use two pointers to find subarrays with sum divisible by k.
D. Use the original prefix sum approach without changes, as sum equals k and sum divisible by k are equivalent.

Solution

  1. Step 1: Understand the problem variant

    We want subarrays where sum % k == 0, not sum == k.
  2. Step 2: Modify prefix sums to track remainders

    Compute prefix sums modulo k and count how many prefix sums have the same remainder, since difference of prefix sums with same remainder is divisible by k.
  3. Step 3: Use hash map to count frequencies of remainders

    Increment count by frequency of current remainder seen so far.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Sliding window fails with negatives; sorting breaks subarray continuity; original approach doesn't handle divisibility. [OK]
Hint: Use prefix sums modulo k and count remainder frequencies [OK]
Common Mistakes:
  • Trying sliding window with negatives
  • Ignoring modulo operation
  • Assuming sum equals k and divisible by k are same
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard