You are given an array nums that holds only 0s and 1s.
Return the length of the longest stretch of 1s that sit next to each other, with no 0 between them. If there is no 1 at all, the answer is 0.
Example 1
Input: nums = [1, 0, 1, 1, 1, 0, 1] Output: 3 Why: indices 2 to 4 hold three 1s in a row
2 more examples and the constraints
Example 2
Input: nums = [0, 0] Output: 0 Why: there is no 1 anywhere
Example 3
Input: nums = [1, 1, 0, 1] Output: 2 Why: the first two numbers
Constraints
- 1 ≤ length of nums ≤ 100,000
- Each 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.
- Extend from every startO(n²)
- One pass, running countO(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 ones | Verdict |
|---|---|---|---|
| Extend from every start | O(n²) | Mention it, then move on | |
| One pass, running count | O(n) | Best; one read per number |
n = the length of nums.
Edge cases to test
- No 1 at all. [0, 0] gives 0.
- All 1s. [1, 1, 1, 1, 1] gives 5, the whole array.
- Longest run at the end. No 0 closes it, so best must be updated inside the loop, not only on a 0.
- One element. [1] gives 1 and [0] gives 0.
Common mistakes
- Updating best only when a 0 is read, which misses a run at the end of the array.
- Forgetting to reset run to 0 on a 0, so separate runs add up.
- Returning the number of runs, or the total count of 1s, instead of the longest run.
How to talk through it
- 1Clarify. Only 0s and 1s? Is the answer 0 when there is no 1?
- 2Give the brute force. Extend a run from every start; say it is O(n²) on an array of all 1s.
- 3Spot the waste. Each run is walked again from inside itself. One counter that resets on 0 is enough.
- 4Code the one pass. Update run, then best, on every number.
- 5Test out loud. Run all zeros, all ones and a run that ends the array.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?