Skip to content

Contiguous Array

Find the longest subarray with as many 0s as 1s, by counting 0 as -1 and matching running sums.

MediumPrefix Sums
Solve on LeetCode

The problem

You get a binary array nums that holds only 0s and 1s. Return the length of the longest contiguous subarray that contains the same number of 0s and 1s, or 0 if there is none.

Input nums = [1, 1, 0, 1, 0, 0, 1]

Output 6

Indices 0 to 5 hold three 1s and three 0s. A balanced subarray needs an even length, so 7 is impossible.

Input nums = [1, 1, 1]

Output 0

There are no 0s, so no subarray can be balanced.

How to spot the pattern

  • You need a subarray where two kinds of items balance out exactly.
  • Counting 0 as -1 turns "balanced" into "sums to 0", which is a prefix sum question.
  • You want the longest such subarray, so you keep the first index of each running sum.

The idea

Count a 1 as +1 and a 0 as -1. A subarray is balanced exactly when its sum is 0, which happens when the running sum has the same value just before it starts and at its end. So store the first index where each running sum appears; when the same sum shows up again at index i, the stretch after that first index is balanced, and its length is i - first[sum].

Brute force: Count the 0s and 1s of every subarray by extending each start one element at a time, which takes O(n^2) time.

Step by step

  1. 1Start a map with balance 0 at index -1, for the empty prefix.
  2. 2Walk through the array, adding +1 for a 1 and -1 for a 0 to a running balance.
  3. 3If balance was seen before, update the best length with i - first[balance].
  4. 4Otherwise store first[balance] = i, keeping only the earliest index.
  5. 5Return the best length.

See the pattern move

The prefix sums pattern on a small example. Step through it, or press play.

Code

class Solution:
    def findMaxLength(self, nums: List[int]) -> int:
        first = {0: -1}  # balance -> first index where it appeared
        balance = 0  # (number of 1s) - (number of 0s) so far
        best = 0
        for i, num in enumerate(nums):
            balance += 1 if num == 1 else -1
            if balance in first:
                best = max(best, i - first[balance])
            else:
                first[balance] = i
        return best

Complexity

Time

O(n)

Space

O(n)

One pass; the balance always stays between -n and n, so the map has at most 2n + 1 entries.

Watch out for

  • Updating the stored index every time a balance repeats: you need the first index of each balance, because it gives the longest stretch.
  • Forgetting balance 0 at index -1, which misses balanced subarrays that start at index 0.
  • Adding 0 for a 0 instead of -1, so the running sum says nothing about balance.

Follow-up questions

Can you avoid the hash map?

Yes. The balance is always between -n and n, so an array of size 2n + 1, indexed by balance + n and filled with a marker for "not seen", works as the map.

What if you had to count the balanced subarrays instead of finding the longest?

Store how many times each balance has appeared and add that count at every step. It is Subarray Sum Equals K with k = 0, after turning each 0 into -1.

In Hinglish

0 ko -1 maan lo. Jab running sum dobara wahi value pe aaye, beech ka hissa balanced hai; isliye har sum ka pehla index yaad rakho.

Related problems