Contiguous Array

Medium

Topics
ArrayHash TablePrefix Sum

Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0s and 1s.

Example 1

0011length 2
Counting a 0 as −1 and a 1 as +1 turns "equal numbers of each" into "running total returns to a value it already had". The braced run has length 2, found by storing the first index at which each running total appeared.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [0,1]
Output: 2
Explanation: [0,1] is the longest subarray with equal counts.

Example 2

001102length 2
Input:  nums = [0,1,0]
Output: 2

Example 3

0001120304051617length 6
Input:  nums = [0,0,1,0,0,0,1,1]
Output: 6

Constraints

  • 1 <= nums.length <= 10^5
  • nums[i] is either 0 or 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

Map every 0 to -1 and the question becomes "longest subarray with sum zero", which prefix sums answer directly: a subarray sums to zero exactly when its two boundary prefixes are equal. So record the first index at which each prefix value appears, and every later occurrence of the same value gives a candidate length.

Approach

  1. Walk the array keeping a running sum, adding +1 for a 1 and -1 for a 0.
  2. Keep a map from prefix value to the earliest index where it occurred. Seed it with {0: -1} so a subarray starting at index 0 is counted.
  3. If the current sum has been seen before, the span between the two positions has equal counts - update the best length with i - firstIndex[sum].
  4. If it is new, store it. Never overwrite an existing entry: you want the earliest index to maximise the span.
class Solution:
    def findMaxLength(self, nums):
        first = {0: -1}
        total = 0
        best = 0
        for i, v in enumerate(nums):
            total += 1 if v == 1 else -1
            if total in first:
                best = max(best, i - first[total])
            else:
                first[total] = i
        return best

Dry Run

nums = [0, 1, 0, 0, 1, 1]
Map 0 to -1 and 1 to +1. Then "equal numbers of 0s and 1s" becomes "the running
sum is the same at both ends", so the task is finding the furthest-apart repeat.
  i=0  v=0  running -1   first time, record index 0
  i=1  v=1  running  0   seen at -1   span 2   best 2
  i=2  v=0  running -1   seen at  0   span 2   best 2
  i=3  v=0  running -2   first time, record index 3
  i=4  v=1  running -1   seen at  0   span 4   best 4
  i=5  v=1  running  0   seen at -1   span 6   best 6
answer 6
Two details carry it, and the trace shows both firing.
The {0: -1} seed is a sentinel for "the empty prefix, just before index 0". It is
what lets a subarray that starts at index 0 be measured: i=1 and i=5 both score
against it. Without the seed, [0,1] returns 0 instead of 2.
Only the FIRST index of each running sum is stored. Overwriting with the latest
shrinks every later span -- this input then returns 4 instead of 6, because the
-1 at index 2 would have replaced the one at index 0 and i=4 would measure a span
of 2.
A sliding window cannot do this. The running sum is not monotone, so there is no
condition under which shrinking from the left is known to help.

Complexity

  • Time — O(n) — one pass, O(1) map work per element.
  • Space — O(n) for the prefix map.

Common Pitfalls

  • Seed the map with {0: -1}. Without it you miss every answer that starts at index 0.
  • Store the first index per prefix, not the latest. Overwriting shrinks every span and quietly returns a too-small answer.
  • A sliding window cannot solve this: the running sum is not monotone, so there is no valid shrink condition.
  • Same transformation, different question: see Subarray Sum Equals K, which counts subarrays instead of measuring one.

Full Solution — all languages

class Solution:
    def findMaxLength(self, nums):
        first = {0: -1}
        running = 0
        best = 0
        for i, v in enumerate(nums):
            running += 1 if v == 1 else -1
            if running in first:
                best = max(best, i - first[running])
            else:
                first[running] = i
        return best
Asked at Morgan Stanley
SensAI
Beta
Tap the mic to stop voice mode