Contiguous Array

MediumPrefix Sum · Hash Map🧩 Prefix SumLeetCode #525 ↗Updated

Problem

You are given a binary array nums (only 0s and 1s). Return the length of the longest contiguous subarray containing the same number of 0s and 1s, or 0 if none exists.
Input[0,1]Output2
Input[0,1,0]Output2
Input[0,1,1,1,1,1,0,0,0]Output6

1 ≤ n ≤ 105  ·  nums[i] ∈ {0, 1}

Try it yourself

Java
class Solution {
    public int findMaxLength(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Count a 0 as -1 and a 1 as +1. “Equal 0s and 1s” becomes “sum = 0”, i.e. two positions with the same running balance. Remember where each balance first appeared.
PatternPrefix Sum

Instinct Repeated range-sum queries, or "count subarrays whose sum equals / divides K" with negatives allowed? Store running totals and subtract two of them.

Memory hack Any range is two prefixes apart - sum(i..j) = P[j+1] - P[i], so remember every P you've passed.

Open the Prefix Sum guide →

Approaches

Brute ForceCount Every Subarray

Time O(n3)Space O(1)

For every (start, end) pair, count the zeros and ones inside with a fresh loop. If the counts match, update the best length.

Java
public int findMaxLength(int[] nums) {
    int best = 0;
    for (int start = 0; start < nums.length; start++) {
        for (int end = start; end < nums.length; end++) {
            int zeros = 0, ones = 0;
            for (int m = start; m <= end; m++) {
                if (nums[m] == 0) zeros++; else ones++;
            }
            if (zeros == ones) best = Math.max(best, end - start + 1);
        }
    }
    return best;
}

Direct translation of the statement; cubic and hopeless at 105.

At a glance

LevelApproachTimeSpace
Brute ForceCount Every SubarrayO(n3)O(1)
BetterRunning Balance per StartO(n2)O(1)
OptimalPrefix Balance + First-Index MapO(n)O(n)
Common pitfalls
  • Overwriting the stored index — keep the first occurrence to get the longest span.
  • Missing the {0: -1} seed → balanced prefixes like [0,1] are lost.
  • Length is i - j, not i - j + 1 (j is before the subarray).
Interview tips
  • Say the ±1 transformation out loud — it reduces the problem to “sum = 0”.
  • Contrast with Subarray Sum = K: here store first index (longest), there store counts.
  • Offer the array-instead-of-map optimisation as a follow-up.
Pattern
Prefix sum + first-occurrence map → longest subarray with a target sum (after mapping values to ±1).
My notes saved in this browser