Longest Contiguous Streak of Ones
Medium · Coding & Algorithms · Machine Learning Engineer · Onsite
Problem Statement
You are given an integer list nums whose entries are strictly 0 or 1. Compute the maximum number of adjacent 1s that appear back-to-back in nums.
You must inspect the sequence as-is without modifying or flipping any 0 entries. Return 0 whenever nums has length zero or contains only 0s.
def find_longest_run_of_ones(nums: list[int]) -> int:
pass
Examples
Example 1
Input: nums = [0, 1, 1, 0, 1, 1, 1, 1, 0, 1]
Output: 4
Walk-through: Reading from left to right, the contiguous groups of 1s have sizes 2 (indices 1..2), 4 (indices 4..7), and 1 (index 9). The largest group has size 4.
Example 2
Input: nums = [1, 1, 1, 0, 0, 1, 1]
Output: 3
Walk-through: An opening streak of three 1s is broken by two 0s and followed by a closing streak of two 1s, giving a maximum streak of 3.
Example 3
Input: nums = [0, 0, 0, 0, 0]
Output: 0
Walk-through: Because 1 never occurs in nums, the longest streak length is 0.
Constraints
0 <= len(nums) <= 10^7- Every element
nums[i]is either0or1. - An empty input
[]must evaluate to0. - Target time complexity:
O(n) - Target auxiliary space complexity:
O(1)
Step-by-step walkthrough
Understand the goal and the memory constraint
We are given a binary list
numscontaining only0s and1s, and we cannot flip any bits. A run of ones is a contiguous slice of adjacent1s with no0inside it. We must return the length of the longest run, or0ifnumsis empty or contains no1s.Look closely at the constraints:
len(nums)can be up to10^7(ten million elements).- Expected time: O(n) — we can only afford a constant amount of work per element.
- Expected auxiliary space: O(1) — our extra working memory cannot grow with
len(nums), so we cannot build a string ("".join(...)), copy subarrays, or collect all run lengths into a list.
Why recounting from every index is too slow
A beginner's first instinct is often to treat every index
startas the start of a potential streak and walk right until hitting a0or the end of the array:def longest_run_brute(nums: list[int]) -> int: max_run = 0 for start in range(len(nums)): length = 0 while start + length < len(nums) and nums[start + length] == 1: length += 1 if length > max_run: max_run = length return max_runWatch what happens when
nums = [1, 1, 1, 1]:start = 0: [1, 1, 1, 1] -> walks 4 elements start = 1: [1, 1, 1] -> walks the same 3 elements again start = 2: [1, 1] -> walks the same 2 elements again start = 3: [1] -> walks the last element a 4th timeA single block of
Lones gets scannedL + (L - 1) + ... + 1 = L * (L + 1) / 2times. On ten million1s, that is roughly5 * 10^13operations. Instead of starting over at every index, we should carry the streak count forward as we move left to right.Key idea: carry two integer counters in one pass
As we scan
numsfrom left to right, we only need two integers:current_run: how many consecutive1s end right at the element we just read.- Seeing
1extends the active streak:current_run += 1. - Seeing
0breaks the streak immediately:current_run = 0.
- Seeing
max_run: the largest valuecurrent_runhas reached anywhere so far, initialized to0.
Because we visit each element once and store only two integers, time drops to O(n) and extra memory drops to O(1).
Why we update max_run on every 1 instead of waiting for a 0
Where should we compare
current_runagainstmax_run? Compare the two choices onnums = [0, 1, 1, 1]:Choice A — Update max_run only when a 0 arrives (BUGGY without post-loop fix): bit = 0 -> update max_run = max(0, 0) = 0, reset current_run = 0 bit = 1 -> current_run = 1 bit = 1 -> current_run = 2 bit = 1 -> current_run = 3 (loop ends with no trailing 0 -> returns max_run = 0 instead of 3!) Choice B — Update max_run immediately on every 1 (ALWAYS UP TO DATE): bit = 0 -> current_run = 0, max_run = 0 bit = 1 -> current_run = 1 -> max_run = 1 bit = 1 -> current_run = 2 -> max_run = 2 bit = 1 -> current_run = 3 -> max_run = 3 (loop ends -> max_run is already 3, no extra check needed after the loop)Updating
max_runright inside theif bit == 1:branch keepsmax_runaccurate after every single step, whether the winning streak ends in the middle of the array or at the very last index.def find_longest_run_of_ones(nums: list[int]) -> int: # max_run: int storing the longest streak of consecutive 1s seen anywhere so far. # Starting at 0 naturally returns 0 for an empty list or an array of all 0s. max_run = 0 # current_run: int storing the length of the active streak of 1s ending at this element. current_run = 0 # Single left-to-right pass over the binary array in O(n) time and O(1) extra space. for bit in nums: if bit == 1: current_run += 1 # Update max_run immediately on every 1 (rather than waiting for a 0) # so a streak that reaches the very end of nums is never missed. if current_run > max_run: max_run = current_run else: # A 0 breaks the contiguous streak, so reset the active streak counter. current_run = 0 return max_runTrace Example 1 step by step
Let's trace
nums = [0, 1, 1, 0, 1, 1, 1, 1, 0, 1]from Example 1:Start: current_run = 0, max_run = 0 Index: 0 1 2 3 4 5 6 7 8 9 nums: [ 0, 1, 1, 0, 1, 1, 1, 1, 0, 1 ] | | | | | | | | | | current_run: 0 -> 1 -> 2 -> 0 -> 1 -> 2 -> 3 -> 4 -> 0 -> 1 max_run: 0 -> 1 -> 2 -> 2 -> 2 -> 2 -> 3 -> 4 -> 4 -> 4 ^ ^ ^ 0 resets new peak 0 resets current_run, current_run of 4 saved while max_run stays 4 Return max_run = 4.Check Example 2 (
[1, 1, 1, 0, 0, 1, 1]):max_runreaches3at index2and stays3when the closing pair of1s reaches2. Check Example 3 ([0, 0, 0, 0, 0]): every element takes theelsebranch, keepingmax_run = 0. An empty input[]skips the loop completely and returns0.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def find_longest_run_of_ones(nums: list[int]) -> int: # max_run: int storing the longest streak of consecutive 1s seen anywhere so far. # Starting at 0 naturally returns 0 for an empty list or an array of all 0s. max_run = 0 # current_run: int storing the length of the active streak of 1s ending at this element. current_run = 0 # Single left-to-right pass over the binary array in O(n) time and O(1) extra space. for bit in nums: if bit == 1: current_run += 1 # Update max_run immediately on every 1 (rather than waiting for a 0) # so a streak that reaches the very end of nums is never missed. if current_run > max_run: max_run = current_run else: # A 0 breaks the contiguous streak, so reset the active streak counter. current_run = 0 return max_run✅ Submit now — all tests should pass.
Intuition & how it works
Imagine tracking your longest workout streak on a wall calendar using just two sticky notes: one for your current streak and one for your best streak ever. Each day you work out (1), you add 1 to your current streak and immediately update your best-streak note if today's streak beat the old record. Each rest day (0), you wipe the current-streak note back to 0, while the best-streak note keeps your record safe.
A naive nested loop starts a new scan from every index, recounting the same 1s again and again and taking quadratic O(n^2) time — around 5 * 10^13 operations when n = 10^7. Another tempting shortcut converts the array into a string like "".join(map(str, nums)).split("0"), which finishes in linear time but allocates new strings proportional to n, violating the O(1) auxiliary space rule (auxiliary space is the extra working memory an algorithm uses beyond the input itself). Carrying two integer counters scans every element once with constant memory.
Walk through a tiny 4-element example, nums = [1, 0, 1, 1], starting with current_run = 0 and max_run = 0:
- Index
0(1):current_runbecomes1,max_runupdates to1. - Index
1(0):current_runresets to0,max_runstays1. - Index
2(1):current_runbecomes1,max_runstays1. - Index
3(1):current_runbecomes2,max_runupdates to2. Loop finishes and returns2.
Complexity
- Time: O(n) where
n = len(nums). We read each element ofnumsexactly once and perform at most two integer comparisons, one addition, and one assignment per element. - Auxiliary space: O(1). Regardless of whether
numshas0elements or10^7elements, we only allocate two integer variables (max_runandcurrent_run).
Edge cases
- Empty list (
[]): The loop never executes andmax_runreturns its initial value0. - All zeros (
[0, 0, 0, 0, 0]): Every element takes theelsebranch, somax_runstays0. - All ones (
[1, 1, 1, 1]):current_runclimbs on every element andmax_runfinishes atlen(nums). - Longest streak at index
0or at the final index: Updatingmax_runon every1handles a streak that touches the end of the array without needing a post-loop check. - Alternating bits (
[1, 0, 1, 0]): Every streak resets after length1, returning1. - Tied streaks (
[1, 1, 0, 1, 1]): Both have length2, andcurrent_run > max_runkeeps2.
Common mistakes
- Updating
max_runonly when seeing a0: Misses any streak that reaches the end of the array (for example, returning0on[0, 1, 1, 1]) unless you also remembermax_run = max(max_run, current_run)after the loop. - Forgetting to reset
current_runon0: Counts the total number of1s in the entire array instead of the longest contiguous streak. - Initializing
max_run = -1orfloat("-inf"): Causes empty or all-zero arrays to return a negative value instead of0. - Building a string or list of run lengths: Works on small inputs, but allocates O(n) extra memory on
10^7elements.
Alternative approaches
itertools.groupby: Python'sgroupby(nums)lazily groups adjacent identical elements in O(n) time and O(1) auxiliary space (max((sum(1 for _ in group) for bit, group in groupby(nums) if bit == 1), default=0)), though the explicit two-counter loop is faster in CPython and easier to explain in an interview.- Vectorized NumPy boundaries: Padding with
0on both ends (padded = np.r_[0, nums, 0]) and takingnp.diff(padded)marks run starts with+1and run ends with-1, running very fast in C for10^7elements at the cost of O(n) extra array memory.
Follow-up questions
- Suppose a massive bit array is partitioned into ordered contiguous shards across cluster workers; what summary record must each worker return so a coordinator can merge them into the overall longest streak? Each worker scans its shard once in O(shard_size) time and emits
(shard_len, prefix_ones, suffix_ones, best_run)— the shard's element count, leading1s, trailing1s, and longest internal streak — tagged with its shard number so left-to-right order is preserved. Combining two adjacent summariesleftandrighttakes O(1) work: the mergedbest_runismax(left.best_run, right.best_run, left.suffix_ones + right.prefix_ones)(capturing a streak that crosses the shard boundary),prefix_onesextends intoright.prefix_onesonly whenleftis entirely1s (left.prefix_ones == left.shard_len), andsuffix_onesextends intoleft.suffix_onesonly whenrightis entirely1s. Because this pairwise combine step is associative (any grouping of adjacent neighbors yields the same result),Mworker summaries can be reduced in parallel in O(M) total work. - How would your design change if bits arrive as an unbounded live stream and callers ask either for the best streak seen since startup or for the best streak within the most recent W bits? For the all-time best streak, the exact same two scalars (
current_runandmax_run) handle an infinite stream in O(1) time per bit and O(1) memory. For a rolling window over the latestWbits, old streaks age out: if queries are rare, a ring buffer (a fixed-length circular array of sizeW) uses O(W) memory and O(W) scan time per query. For O(1) amortized updates and O(1) queries, maintain finished(start, end)streaks in a monotonic deque (a double-ended queue kept in strictly decreasing order of streak length by popping shorter older streaks from the back, while dropping expired streaks withend < window_startfrom the front): each query takes the max of the front streak clipped towindow_start, the second deque entry (guaranteed fully inside the window), and the livecurrent_runclipped towindow_start, needing at most O(√W) space because disjoint streaks of strictly decreasing lengths insideWpositions satisfy1 + 2 + ... + m <= W. - If you may convert up to k zeros into ones, what algorithm finds the longest achievable streak and how do the time and memory bounds change? Both bounds remain O(n) time and O(1) auxiliary space by using a sliding window (two indices
leftandrightbounding the current valid slicenums[left..right]) alongside an integerzero_count. Advancerightone position per iteration, incrementingzero_countwhenevernums[right] == 0, and whilezero_count > k, advanceleft(decrementingzero_countwhenevernums[left] == 0) until at mostkzeros remain inside the window, updatingbest = max(best, right - left + 1). Becauseleftandrighteach advance at mostnsteps across the entire loop, runtime stays linear; only when reading a one-pass unbuffered stream does auxiliary memory grow to O(k) to store the positions of the latestk + 1zeros.
Follow-up questions
- Suppose a massive bit array is partitioned into ordered contiguous shards across cluster workers; what summary record must each worker return so a coordinator can merge them into the overall longest streak?
- How would your design change if bits arrive as an unbounded live stream and callers ask either for the best streak seen since startup or for the best streak within the most recent W bits?
- If you may convert up to k zeros into ones, what algorithm finds the longest achievable streak and how do the time and memory bounds change?
Similar questions
- Longest Consecutive Ones Across Sharded Machines
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One