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 either 0 or 1.
  • An empty input [] must evaluate to 0.
  • Target time complexity: O(n)
  • Target auxiliary space complexity: O(1)

Step-by-step walkthrough

  1. Understand the goal and the memory constraint

    We are given a binary list nums containing only 0s and 1s, and we cannot flip any bits. A run of ones is a contiguous slice of adjacent 1s with no 0 inside it. We must return the length of the longest run, or 0 if nums is empty or contains no 1s.

    Look closely at the constraints:

    • len(nums) can be up to 10^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.
  2. Why recounting from every index is too slow

    A beginner's first instinct is often to treat every index start as the start of a potential streak and walk right until hitting a 0 or 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_run
    

    Watch 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 time
    

    A single block of L ones gets scanned L + (L - 1) + ... + 1 = L * (L + 1) / 2 times. On ten million 1s, that is roughly 5 * 10^13 operations. Instead of starting over at every index, we should carry the streak count forward as we move left to right.

  3. Key idea: carry two integer counters in one pass

    As we scan nums from left to right, we only need two integers:

    • current_run: how many consecutive 1s end right at the element we just read.
      • Seeing 1 extends the active streak: current_run += 1.
      • Seeing 0 breaks the streak immediately: current_run = 0.
    • max_run: the largest value current_run has reached anywhere so far, initialized to 0.

    Because we visit each element once and store only two integers, time drops to O(n) and extra memory drops to O(1).

  4. Why we update max_run on every 1 instead of waiting for a 0

    Where should we compare current_run against max_run? Compare the two choices on nums = [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_run right inside the if bit == 1: branch keeps max_run accurate 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_run
    
  5. Trace 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_run reaches 3 at index 2 and stays 3 when the closing pair of 1s reaches 2. Check Example 3 ([0, 0, 0, 0, 0]): every element takes the else branch, keeping max_run = 0. An empty input [] skips the loop completely and returns 0.

  6. 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_run becomes 1, max_run updates to 1.
  • Index 1 (0): current_run resets to 0, max_run stays 1.
  • Index 2 (1): current_run becomes 1, max_run stays 1.
  • Index 3 (1): current_run becomes 2, max_run updates to 2. Loop finishes and returns 2.

Complexity

  • Time: O(n) where n = len(nums). We read each element of nums exactly once and perform at most two integer comparisons, one addition, and one assignment per element.
  • Auxiliary space: O(1). Regardless of whether nums has 0 elements or 10^7 elements, we only allocate two integer variables (max_run and current_run).

Edge cases

  • Empty list ([]): The loop never executes and max_run returns its initial value 0.
  • All zeros ([0, 0, 0, 0, 0]): Every element takes the else branch, so max_run stays 0.
  • All ones ([1, 1, 1, 1]): current_run climbs on every element and max_run finishes at len(nums).
  • Longest streak at index 0 or at the final index: Updating max_run on every 1 handles 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 length 1, returning 1.
  • Tied streaks ([1, 1, 0, 1, 1]): Both have length 2, and current_run > max_run keeps 2.

Common mistakes

  • Updating max_run only when seeing a 0: Misses any streak that reaches the end of the array (for example, returning 0 on [0, 1, 1, 1]) unless you also remember max_run = max(max_run, current_run) after the loop.
  • Forgetting to reset current_run on 0: Counts the total number of 1s in the entire array instead of the longest contiguous streak.
  • Initializing max_run = -1 or float("-inf"): Causes empty or all-zero arrays to return a negative value instead of 0.
  • Building a string or list of run lengths: Works on small inputs, but allocates O(n) extra memory on 10^7 elements.

Alternative approaches

  • itertools.groupby: Python's groupby(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 0 on both ends (padded = np.r_[0, nums, 0]) and taking np.diff(padded) marks run starts with +1 and run ends with -1, running very fast in C for 10^7 elements 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, leading 1s, trailing 1s, and longest internal streak — tagged with its shard number so left-to-right order is preserved. Combining two adjacent summaries left and right takes O(1) work: the merged best_run is max(left.best_run, right.best_run, left.suffix_ones + right.prefix_ones) (capturing a streak that crosses the shard boundary), prefix_ones extends into right.prefix_ones only when left is entirely 1s (left.prefix_ones == left.shard_len), and suffix_ones extends into left.suffix_ones only when right is entirely 1s. Because this pairwise combine step is associative (any grouping of adjacent neighbors yields the same result), M worker 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_run and max_run) handle an infinite stream in O(1) time per bit and O(1) memory. For a rolling window over the latest W bits, old streaks age out: if queries are rare, a ring buffer (a fixed-length circular array of size W) 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 with end < window_start from the front): each query takes the max of the front streak clipped to window_start, the second deque entry (guaranteed fully inside the window), and the live current_run clipped to window_start, needing at most O(√W) space because disjoint streaks of strictly decreasing lengths inside W positions satisfy 1 + 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 left and right bounding the current valid slice nums[left..right]) alongside an integer zero_count. Advance right one position per iteration, incrementing zero_count whenever nums[right] == 0, and while zero_count > k, advance left (decrementing zero_count whenever nums[left] == 0) until at most k zeros remain inside the window, updating best = max(best, right - left + 1). Because left and right each advance at most n steps 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 latest k + 1 zeros.

Follow-up questions

Similar questions

More Molocoads interview questions

All 2 Molocoads questions →