We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A medium prefix sum problem, graded against 6 test cases (3 of them hidden).
Precomputed cumulative totals so any range query becomes one subtraction.
Reach for it when you see: Repeated range-sum queries, or counting subarrays that sum to a target.
More Prefix Sumproblems →Counting two things at once is awkward. Map `0` to `-1` and `1` to `+1` and the condition collapses: a subarray has equal counts exactly when it sums to zero.
A subarray sums to zero when the running prefix has the same value at both ends. So sweep once, and the first time you see a prefix value, record its index; every later re-appearance of that value marks a balanced subarray, whose length is the index distance. Keeping only the first index for each value is what maximizes the length - a later occurrence would only ever produce a shorter span.
The seed `prefix 0 -> index -1` handles subarrays that start at index 0. Without it, `[0,1]` returns 0 instead of 2, which is the classic off-by-one in this problem.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.