Contiguous Array (LeetCode 525): Solution and Explanation

Medium
Array
Hash Table
Prefix Sum

Given an array of 0s and 1s, find the length of the longest contiguous subarray that has the same number of 0s and 1s. Return 0 if there is none.

Intuition

Counting 0s and 1s for every subarray is O(n^2). The trick is to replace the two counts with one number: add 1 for every 1 and subtract 1 for every 0. A subarray is balanced exactly when this running balance ends where it started.

Picture the balance as a walk that goes up on 1 and down on 0, starting at height 0 before index 0. Any two points of the walk at the same height enclose a balanced subarray, because the ups and downs between them cancel.

To get the longest such subarray ending at index i, pair i with the earliest index that reached the same height. So store the first index of every height and never overwrite it.

Seeding height 0 at index -1 lets balanced subarrays that start at index 0 be measured too.

Approach: Running balance with first-seen index

  1. Create first = {0: -1} and set count = 0, best = 0.
  2. For each index i, add 1 to count if nums[i] is 1, otherwise subtract 1.
  3. If count is already in first, update best = max(best, i - first[count]).
  4. Otherwise store first[count] = i.
  5. Return best.

Step-by-step example

nums = [0,1,1,1,1,1,0,0,0]
  1. Start with first = {0: -1}, count = 0.
  2. i = 0: 0 steps down to -1, new, store first[-1] = 0.
  3. i = 1: 1 steps up to 0, seen at -1, so best = 1 - (-1) = 2.
  4. i = 2..5: the walk climbs to 1, 2, 3, 4, each a new height stored at its index.
  5. i = 6: down to 3, first seen at 4, length 2. i = 7: down to 2, first at 3, length 4.
  6. i = 8: down to 1, first at 2, length 6. best = 6, which is the answer.

Code: Python, Java, C++

1class Solution:
2    def findMaxLength(self, nums: List[int]) -> int:
3        first = {0: -1}
4        count = 0
5        best = 0
6        for i, num in enumerate(nums):
7            count += 1 if num == 1 else -1
8            if count in first:
9                best = max(best, i - first[count])
10            else:
11                first[count] = i
12        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass with constant-time map operations per element.

Space

O(n)

The balance takes at most 2n + 1 distinct values, and each first occurrence is stored once. An array of size 2n + 1 can replace the map.

Other approaches

Check every subarray (time O(n^2), space O(1))

Fix a start, extend the end while counting zeros and ones, and record the longest run where they are equal.

Offset array instead of hash map (time O(n), space O(n))

The balance always lies in [-n, n], so an int array of size 2n + 1 indexed by balance + n can hold first indices. Same complexity, smaller constant factor.

Common mistakes

  • Forgetting the {0: -1} seed. Without it, [0,1] returns 0 because the balanced prefix has nothing to pair with.
  • Overwriting the stored index on a repeat. The answer needs the earliest index for each balance, otherwise lengths shrink.
  • Counting 0 as 0 instead of -1. Then the sum never goes down and equal counts cannot be detected.
  • Using a sliding window. Balance is not monotonic, so shrinking from the left does not work here.

Frequently asked questions

Why does an equal balance mean equal 0s and 1s?

The balance changes by +1 per 1 and -1 per 0. If it is the same at two points, the elements between them added as many +1s as -1s, which means the same number of 1s and 0s.

Is this the same idea as Subarray Sum Equals K?

Yes. After mapping 0 to -1, you are looking for the longest subarray with sum 0, which is a prefix sum plus hash map problem. Here you store the first index instead of a count.

Can the answer be odd?

No. A balanced subarray has as many 0s as 1s, so its length is always even. The answer is 0 when every element is the same.