#525

Contiguous Array

Medium Prefix sum + first index

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

In a binary array, find the length of the longest contiguous subarray with equally many 0s and 1s.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: longest piece with equal 0s and 1s.

Why this works: count 0 as -1. Equal counts means the piece sums to 0, which happens when the same running sum appears twice. Remember where each sum first appeared.

Example: [0, 1, 0]

sums: -1, 0, -1   (start: 0 at index -1)index 1: sum 0 seen at -1 → length 2index 2: sum -1 seen at 0 → length 2answer 2

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Overwriting the stored index with later occurrences — you need the earliest to get the longest length.