You are given an array nums in which every value is either 0 or 1.
Find the longest stretch of neighbouring positions that holds as many 0s as 1s, and return its length. If no such stretch exists, return 0.
Example 1
Input: nums = [1, 1, 0, 1, 0, 0, 1] Output: 6 Why: positions 1 to 6 hold three 1s and three 0s
2 more examples and the constraints
Example 2
Input: nums = [1, 1, 1] Output: 0 Why: there is no 0, so no stretch can balance
Example 3
Input: nums = [0, 0, 1, 0] Output: 2 Why: [0, 1] or [1, 0]; no longer stretch balances
Constraints
- 1 ≤ length of nums ≤ 100,000
- Every nums[i] is 0 or 1
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Every start, grow the endO(n²)
- Running balance + first indexO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 values | Verdict |
|---|---|---|---|
| Every start, grow the end | O(n²) | Mention it, then move on | |
| Running balance + first index | O(n) | Best; one pass |
n = length of nums.
Edge cases to test
- Only one kind of value. [1, 1, 1] has no balanced stretch, so the answer is 0.
- A single value. [0] can never balance; return 0.
- The whole array balances. [0, 1, 1, 0] gives 4. The stored −1 for balance 0 is what makes that work.
- Alternating values. [1, 0, 1, 0, 1, 0] balances end to end: 6.
Common mistakes
- Forgetting to store balance 0 at index −1, which misses every stretch that starts at position 0.
- Updating the stored index every time a balance appears, so stretches come out shorter than they are.
- Counting 0s as 0 instead of −1, so the running sum can never tell equal counts apart.
How to talk through it
- 1Clarify. Are the values only 0 and 1? Should an array with no balanced stretch return 0?
- 2Give the brute force. Try every start and grow the end with a running balance: O(n²).
- 3Turn it into a sum. Map 0 to −1. Equal counts now mean the stretch sums to 0, so two equal prefix balances mark one.
- 4Code the map. Keep the first index of each balance, seeded with 0 → −1, and measure i minus that index.
- 5Test out loud. Run [1, 1, 1], [0] and a whole-array answer like [0, 1, 1, 0] before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?