Longest Consecutive Ones Across Sharded Machines

Medium · System Design · Machine Learning Engineer · Onsite

Prompt

A massive sequence of bits (0 and 1) is split in order across N worker nodes (S_1 on node 1, S_2 on node 2, ..., S_N on node N), forming one logical concatenation S_1 + S_2 + ... + S_N. Design a distributed system and aggregation algorithm that determines the exact length of the longest unbroken streak of 1s anywhere in the combined stream.

Because the global sequence preserves node order, the winning streak of 1s might sit inside a single node, cross the seam between two adjacent nodes, or stretch continuously across one or more intermediate nodes whose slices contain nothing but 1s.

Your design must satisfy three constraints:

  • Every worker scans its own local slice S_i in one pass without transferring raw bit sequences over the network.
  • Combining two adjacent range descriptors must use an associative merge function so the cluster can aggregate partial descriptors in parallel through a hierarchical reduction tree.
  • Edge cases such as empty slices and slices consisting solely of 1s must produce exact results.

For illustration, consider N = 3 ordered slices:

  • S_1 = [0, 1, 1, 0, 1, 1] (local longest streak is 2, ending with two trailing 1s)
  • S_2 = [1, 1] (every bit in this slice is 1, length 2)
  • S_3 = [1, 0, 1, 1, 1] (begins with one leading 1, local longest streak is 3)

Across S_1 + S_2 + S_3, the two trailing 1s of S_1, both 1s of S_2, and the leading 1 of S_3 connect into a contiguous streak of length 2 + 2 + 1 = 5, exceeding every single-node maximum.

Scope & Expectations

  • Per-slice descriptor & single-pass scan: Specify the exact constant-size fields each worker computes locally in one pass and show how all-1 slices and empty slices are represented.
  • Associative merge operator: Define the deterministic rule for combining two adjacent descriptors left-to-right and explain why parenthesizing merges in different tree orders yields identical outputs.
  • Cluster execution & sizing: Estimate local disk versus network costs, define worker/reducer RPC contracts, and lay out the distributed tree-reduction workflow across N machines.
  • Resilience & streaming extensions: Address straggler mitigation, node crash recovery without full-cluster rescans, and incremental updates if new bits continue arriving.

Step-by-step walkthrough

  1. Clarify requirements and edge cases

    A shard is one ordered slice of a large dataset stored on its own machine. Here, a huge binary stream of 0s and 1s is split across N machines in a known sequence (S_1 followed by S_2, ..., followed by S_N), and we want the exact length of the longest unbroken streak of 1s in the combined stream S_1 + S_2 + ... + S_N.

    Concrete assumptions to agree on first

    • Scale: N = 1,000 machines, each holding up to 10^10 bits (10 billion bits). Stored bit-packed—meaning 8 bits are packed into each byte instead of wasting an entire byte per 0 or 1—each shard is 1.25 GB, and the whole stream is 1.25 TB.
    • Output: The exact integer length of the longest consecutive run of 1s across the entire ordered stream (with an optional extension to also return the global starting bit index).
    • Workload: Start with a batch computation over an immutable snapshot, then extend the exact same data structure to a live streaming shard where new bits keep arriving.
    • Known ordering: A coordinator knows each machine's shard index 1..N. Order matters because runs of 1s can cross shard boundaries.

    Functional requirements

    • Each machine scans its local shard once, independently, producing a constant-size summary.
    • A merge(left, right) function combines summaries of two adjacent ranges into one summary for their concatenation.
    • merge must be associative—meaning grouping merges in different tree shapes, such as merge(merge(A, B), C) versus merge(A, merge(B, C)), always yields the exact same result—so the system can aggregate summaries in parallel using a tree.

    Non-functional requirements and critical edge cases

    • End-to-end latency should stay close to the time of a single local disk scan, moving kilobytes over the network rather than terabytes.
    • If one machine crashes, recovery should rescan at most the lost shard (or uncheckpointed portion of it), never the entire 1.25 TB stream.
    • Must-handle edge cases: a run bridging two neighbours, a shard made entirely of 1s (allowing a run to start on machine i - 1, pass straight through machine i, and continue into machine i + 1), an empty shard (0 bits), and N = 1.
  2. Back-of-the-envelope numbers

    Before choosing an architecture, let's check what takes time and bandwidth:

    Local scan per machine (1,000 machines running in parallel)
      Bits per shard:        10^10 bits = 1.25 GB bit-packed (10 GB if 1 byte per bit)
      Local NVMe read speed: ~1.25 GB/s -> ~1.0 s per shard (all 1,000 finish in ~1 s)
      Scanner RAM needed:    O(1) — just a handful of 64-bit integer counters
    
    Why shipping raw data fails
      Total raw stream:      1,000 x 1.25 GB = 1.25 TB
      Over one 10 Gbps link: ~1.25 GB/s max -> ~1,000 s (~17 minutes) just in network transfer
    
    Shard summary size
      Core counters:         4 x 64-bit integers = 32 bytes
                             (64-bit is required: 10^10 bits > 2.14 x 10^9 max of 32-bit int)
      RPC envelope:          ~64 bytes including shard range and data_version metadata
      All 1,000 summaries:   1,000 x 64 B = 64 KB total across the entire cluster
    
    Reduction cost across N = 1,000 summaries
      Flat central fold:     999 merges in coordinator RAM -> a few microseconds of CPU
      Binary reduction tree: ceil(log2(1000)) = 10 levels; at ~1 ms per network hop -> ~10 ms
    

    Two practical insights fall right out of these numbers:

    1. The local disk scan dominates total runtime (~1 second vs milliseconds for reduction). The real engineering leverage is keeping summaries tiny and making the local scan multi-core, byte-at-a-time, and checkpointed.
    2. At N = 1,000, even one coordinator could merge all 64 KB, whereas a hierarchical reduction tree pays off when N grows to 100,000+ shards (avoiding TCP connection storms on one node), when aggregating within each datacenter rack first, or when maintaining live streaming updates in O(log N) merges.
  3. Component APIs and RPC contracts

    An RPC (Remote Procedure Call) is a structured request-response function call sent over the network between two machines. Our system needs just three logical roles:

    Worker (runs on each shard host)
      Summarize(job_id, shard_index, data_version) -> RangeSummary
        RangeSummary {
          first_shard:  int64,   # shard_index for a leaf summary
          last_shard:   int64,   # shard_index for a leaf summary
          data_version: int64,   # snapshot ID so stale and fresh shards never mix
          length:       int64,   # total bits in S[first_shard .. last_shard]
          prefix:       int64,   # consecutive 1s starting at the very first bit
          suffix:       int64,   # consecutive 1s ending at the very last bit
          best:         int64    # longest consecutive run of 1s anywhere in range
        }
    
    Reducer (stateless; can run on workers themselves or coordinator)
      Merge(job_id, left: RangeSummary, right: RangeSummary) -> RangeSummary
        preconditions:
          left.data_version == right.data_version
          left.last_shard + 1 == right.first_shard
    
    Coordinator
      RunJob(job_id, shard_hosts[1..N], data_version) -> { longest_run: int64 }
    

    Why enforce left.last_shard + 1 == right.first_shard? Because our merge operation is associative, not commutative (a commutative operation allows swapping its two inputs without changing the answer). Here, swapping shards changes the stream itself: [0, 1] followed by [1, 0] forms [0, 1, 1, 0] (best = 2), whereas [1, 0] followed by [0, 1] forms [1, 0, 0, 1] (best = 1). Attaching [first_shard, last_shard] lets every reducer verify it is joining adjacent ranges in left-to-right order.

  4. Data model: designing the 4-number shard summary

    Let's build the shard summary from scratch by asking what information is needed when two shards meet at a boundary.

    • If we only store best (the longest run inside each shard), [0, 1, 1, 0, 1, 1] (best = 2) followed by [1, 1, 0, 0] (best = 2) misses the seam run of length 2 + 2 = 4.
    • Adding prefix (leading 1s touching the left edge) and suffix (trailing 1s touching the right edge) handles direct two-shard bridges.
    • Why do we also need length? Compare these two middle shards when placed between [0, 1, 1, 0, 1, 1] (suffix = 2) and [1, 0, 1, 1, 1] (prefix = 1):
    Case A (all 1s):         [0, 1, 1, 0, 1, 1] + [1, 1]          + [1, 0, 1, 1, 1]
      Middle shard has:      prefix = 2, suffix = 2, best = 2, length = 2
      Combined stream:       0, 1, 1, 0, [1, 1,  1, 1,  1], 0, 1, 1, 1 -> run passes through! Longest = 5
    
    Case B (has a 0 inside): [0, 1, 1, 0, 1, 1] + [1, 1, 0, 1, 1] + [1, 0, 1, 1, 1]
      Middle shard has:      prefix = 2, suffix = 2, best = 2, length = 5
      Combined stream:       0, 1, 1, 0, [1, 1,  1, 1], 0, [1, 1,  1], 0, 1, 1, 1 -> broken! Longest = 4
    

    Without length, Case A and Case B have identical (prefix, suffix, best) = (2, 2, 2), making it impossible to know whether a streak bridges all the way across the middle machine! With length, a range consists entirely of 1s if and only if prefix == length (which is true exactly when zero 0s appear anywhere in the range).

    Each worker computes its four counters in one linear scan using O(1) memory:

    from typing import List, NamedTuple
    
    
    class Summary(NamedTuple):
        length: int  # total number of bits in this range
        prefix: int  # consecutive 1s starting at the very left edge
        suffix: int  # consecutive 1s ending at the very right edge
        best: int    # longest run of 1s anywhere inside this range
    
    
    # Identity summary representing an empty 0-bit range
    EMPTY = Summary(length=0, prefix=0, suffix=0, best=0)
    
    
    def summarize(bits: List[int]) -> Summary:
        """Scan a local shard once in O(n) time and O(1) extra space."""
        best = 0
        current_run = 0
        prefix = 0
        still_in_prefix = True
    
        for bit in bits:
            if bit == 1:
                current_run += 1
                if current_run > best:
                    best = current_run
                # Keep growing prefix until we hit the very first 0
                if still_in_prefix:
                    prefix += 1
            else:
                current_run = 0
                still_in_prefix = False
    
        # After the loop finishes, current_run is the streak touching the last bit
        suffix = current_run
        return Summary(length=len(bits), prefix=prefix, suffix=suffix, best=best)
    

    Tracing summarize([0, 1, 1, 0, 1, 1]) bit by bit:

    • bit = 0: current_run = 0, still_in_prefix = False, prefix = 0, best = 0
    • bit = 1: current_run = 1, prefix = 0, best = 1
    • bit = 1: current_run = 2, prefix = 0, best = 2
    • bit = 0: current_run = 0, prefix = 0, best = 2
    • bit = 1: current_run = 1, prefix = 0, best = 2
    • bit = 1: current_run = 2, prefix = 0, best = 2
    • Returns Summary(length=6, prefix=0, suffix=2, best=2).
  5. Merge logic and why it is associative

    Now suppose left summarizes S_a..S_b and right summarizes S_{b+1}..S_c. How do the four numbers combine for left followed immediately by right?

    1. length: Total bits simply add up: left.length + right.length.
    2. prefix: Starts at the left edge of left. If left is 100% 1s (left.prefix == left.length), that leading streak continues unbroken into right's leading 1s (left.length + right.prefix). Otherwise, a 0 inside left already stopped it at left.prefix.
    3. suffix: Ends at the right edge of right. Symmetrically, if right is 100% 1s (right.prefix == right.length), right extends left's trailing 1s (left.suffix + right.length). Otherwise, it stops at right.suffix.
    4. best: Any run in the combined range lies completely inside left (left.best), completely inside right (right.best), or crosses the seam between them (left.suffix + right.prefix). Take the maximum of the three.
    def merge(left: Summary, right: Summary) -> Summary:
        """Combine adjacent summaries `left` then `right` in O(1) time."""
        left_all_ones = (left.prefix == left.length)
        right_all_ones = (right.prefix == right.length)
    
        if left_all_ones:
            merged_prefix = left.length + right.prefix
        else:
            merged_prefix = left.prefix
    
        if right_all_ones:
            merged_suffix = left.suffix + right.length
        else:
            merged_suffix = right.suffix
    
        bridge_run = left.suffix + right.prefix
        merged_best = max(left.best, right.best, bridge_run)
        merged_length = left.length + right.length
    
        return Summary(
            length=merged_length,
            prefix=merged_prefix,
            suffix=merged_suffix,
            best=merged_best,
        )
    

    Let's verify both our 3-slice sample and associativity across the all-1s middle bridge (S_1 = [0, 1, 1, 0, 1, 1], S_2 = [1, 1], S_3 = [1, 0, 1, 1, 1]):

    Leaf summaries:
      S1 = [0, 1, 1, 0, 1, 1] -> (len=6, pre=0, suf=2, best=2)
      S2 = [1, 1]             -> (len=2, pre=2, suf=2, best=2)   [all 1s: pre == len]
      S3 = [1, 0, 1, 1, 1]    -> (len=5, pre=1, suf=3, best=3)
    
    Grouping 1: merge(merge(S1, S2), S3)
      merge(S1, S2):  S2 is all 1s, so suffix = 2 + 2 = 4; best = max(2, 2, 2+2) = 4
                      -> (len=8, pre=0, suf=4, best=4)
      merge(.., S3):  bridge = 4 + 1 = 5; best = max(4, 3, 5) = 5
                      -> (len=13, pre=0, suf=3, best=5)
    
    Grouping 2: merge(S1, merge(S2, S3))
      merge(S2, S3):  S2 is all 1s, so prefix = 2 + 1 = 3; best = max(2, 3, 2+1) = 3
                      -> (len=7, pre=3, suf=3, best=3)
      merge(S1, ..):  bridge = 2 + 3 = 5; best = max(2, 3, 5) = 5
                      -> (len=13, pre=0, suf=3, best=5)
    

    Why does associativity hold for every input? Because merge(summarize(A), summarize(B)) always produces the exact summary summarize(A + B) of the concatenated bit sequence A + B. Since string/list concatenation (A + B) + C == A + (B + C) is associative, merge is guaranteed to be associative on all valid summaries! Notice also that EMPTY = (0, 0, 0, 0) satisfies 0 == 0 (all_ones = True), so merge(EMPTY, X) == X and merge(X, EMPTY) == X—making EMPTY a clean identity element (a neutral value that leaves any summary unchanged when merged).

  6. High-level system architecture

    We organize the cluster using a MapReduce pattern—a two-phase distributed design where machines first transform local data independently in parallel ("map") and then combine partial results hierarchically ("reduce"):

                           +-------------------------------------+
                           | Coordinator + Durable KV Store      |
                           | - shard order [1..N], job state     |
                           | - persists leaf & internal summaries|
                           +------------------+------------------+
                                              |
                             assign tasks &   |   final root.best
                             store checkpoints|
                                              v
      Level 3 (Root)              [ Merge(S1..S4, S5..S8) ]
                                      ^               ^
      Level 2             [ Merge(S1..S2, S3..S4) ]   [ Merge(S5..S6, S7..S8) ]
                              ^             ^             ^             ^
      Level 1           [M(S1,S2)]     [M(S3,S4)]     [M(S5,S6)]     [M(S7,S8)]
                          ^    ^         ^    ^         ^    ^         ^    ^
      Map phase          W1    W2       W3    W4       W5    W6       W7    W8
      Local NVMe        [S1]  [S2]     [S3]  [S4]     [S5]  [S6]     [S7]  [S8]
    

    End-to-end execution flow:

    1. Dispatch (Map): The coordinator sends Summarize(job_id, i, data_version) to all N workers simultaneously. Raw shard bytes never leave local NVMe storage.
    2. Local Scan & Persist: Each worker computes its RangeSummary [i..i] and writes the 64-byte record to the coordinator's durable key-value store (a replicated storage service that keeps small records safe across machine crashes).
    3. Hierarchical Reduce: Reducers combine adjacent summaries ([1..1] with [2..2], [3..3] with [4..4], and so on) up the tree. In practice, workers double as reducers—for example, odd worker W1 merges its summary with W2's—which avoids dedicated reducer machines and keeps lower-level merges inside the same datacenter rack.
    4. Return Answer: Once root summary [1..N] is produced, root.best is the global longest run of 1s.
  7. Deep dive 1: order-preserving tree reduction and fast local scanning

    Two practical details turn the textbook algorithm into a high-throughput production job:

    1. Eager neighbour merging vs rigid tree levels

    In a basic level-by-level tree (reduce_tree below), every level waits for its slowest pair. Because merge is associative, the coordinator does not actually need to wait for rigid tree levels! It can maintain a map of completed contiguous ranges keyed by first_shard and last_shard. Whenever a newly completed range [a..b] finds [b+1..c] (or [z..a-1]) already finished, it merges them immediately. When the very last slow shard finishes, at most two merges (with its left finished block and right finished block) remain before the global answer is ready.

    We can also tune fan-in k (how many adjacent summaries one parent reducer merges left-to-right in a single step): k = 10 reduces N = 1,000 shards in ceil(log_10(1000)) = 3 hops instead of 10, and k = 32 handles N = 1,000,000 shards in just 4 hops.

    (Optional extension: if callers also want the global bit offset where the longest run starts, add best_start: int to Summary. On merge(left, right), a bridging run starts at left.length - left.suffix, and a winning run inside right shifts to left.length + right.best_start. Summary size stays O(1) and associativity still holds.)

    2. Accelerating and checkpointing the 1.25 GB local scan

    Since 99% of wall-clock time is spent scanning 1.25 GB on each worker, we reuse the exact same Summary and merge inside each machine:

    • Multi-core chunking: Slice the 1.25 GB file into twenty 64 MB chunks. Sixteen CPU threads scan chunks in parallel and persist (shard_index, chunk_index) -> Summary as checkpoints, then merge the 20 chunk summaries in chunk order 0..19.
    • Byte-table lookup + 64-bit word skipping: Instead of branching on 10 billion individual bits, precompute Summary for all 256 possible byte values (0x00 to 0xFF). A compiled C++ or Rust worker scans whole bytes via table lookup—and skips 64 bits in a single CPU instruction whenever an 8-byte word equals 0x0000000000000000 -> (64, 0, 0, 0) or 0xFFFFFFFFFFFFFFFF -> (64, 64, 64, 64):
    from typing import List
    
    
    def reduce_tree(summaries: List[Summary]) -> Summary:
        """Pairwise order-preserving tree reduction across N shard summaries."""
        if not summaries:
            return EMPTY
        current_level = list(summaries)
        while len(current_level) > 1:
            next_level = []
            # Merge adjacent pairs (0,1), (2,3), ... strictly left before right
            for i in range(0, len(current_level) - 1, 2):
                next_level.append(merge(current_level[i], current_level[i + 1]))
            # Carry an odd trailing summary straight up to the next level
            if len(current_level) % 2 == 1:
                next_level.append(current_level[-1])
            current_level = next_level
        return current_level[0]
    
    
    # Precompute the 4-number summary of all 256 possible 8-bit bytes (MSB first)
    BYTE_SUMMARY = [
        summarize([(byte_val >> shift) & 1 for shift in range(7, -1, -1)])
        for byte_val in range(256)
    ]
    
    
    def summarize_packed_bytes(packed_data: bytes) -> Summary:
        """Scan a bit-packed shard 8 bits at a time using table lookups."""
        acc = EMPTY
        for byte_val in packed_data:
            acc = merge(acc, BYTE_SUMMARY[byte_val])
        return acc
    
  8. Deep dive 2: incremental streaming updates with a segment tree

    What if shards are not static files, and machines continuously append new bits (for instance, tracking consecutive ad-auction wins or health-check successes across shards)? Re-running the reduction over all N shards on every bit would waste work.

    First, appending a single bit to a machine's running summary is just a merge with a 1-bit summary in O(1) time:

    def append_bit(running: Summary, bit: int) -> Summary:
        """Extend a shard's summary by one newly arrived bit in O(1) time."""
        one_bit_summary = Summary(1, 1, 1, 1) if bit == 1 else Summary(1, 0, 0, 0)
        return merge(running, one_bit_summary)
    

    Second, to maintain the global answer when any shard S_i updates, the coordinator keeps the reduction tree in memory as a segment tree—a binary tree over a fixed array where each leaf stores one shard's summary and each internal node stores merge(left_child, right_child):

                           [Root S1..S4]*  <- recomputed (step 2)
                           /            \
                 [S1..S2]*                [S3..S4]   (untouched)
                 /       \                /      \
              [S1]       [S2]*         [S3]      [S4]
                           ^
                   S2 pushes new summary (step 1)
    
    • Each worker updates its local summary per bit in O(1) and pushes changes at most once per second (coalescing millions of bits/s into 1 update/s).
    • When S_2 reports a new summary, the coordinator updates leaf S_2 and recomputes only the ceil(log2(N)) nodes along the path to the root (10 merges for N = 1,000), reading root.best in O(1).
    • Even simpler special case: if only the last active shard S_N receives appends while S_1..S_{N-1} are sealed historical shards, keep a single frozen = Summary(S_1..S_{N-1}) and compute merge(frozen, live_S_N).best in one O(1) merge!
  9. Fault tolerance, stragglers, and key trade-offs

    Handling failures and slow machines without full recomputation

    • Reducer crash: Stateless! Because every leaf and intermediate RangeSummary is persisted in the durable KV store, another reducer fetches the two already-saved child summaries and re-runs merge in microseconds—zero shard data is rescanned.
    • Worker crash mid-scan: Underlying distributed storage (such as HDFS or S3/replicated NVMe) keeps 3x shard replicas. A replacement worker loads the finished 64 MB chunk checkpoints for that shard from the KV store, scans only the missing chunks from a healthy replica, and merges chunks 0..19.
    • Stragglers and speculative execution: A straggler is a single degraded disk or noisy host that runs much slower than peers, holding up the final answer. When a shard scan exceeds 1.5x the median task duration, the coordinator launches speculative execution—a duplicate scan of the remaining chunks on another replica, taking whichever finishes first.
    • Why retries and duplicates are safe: Summarizing (shard_range, data_version) is deterministic and idempotent—meaning writing the result once or overwriting it multiple times leaves the exact same value in summaries[(job_id, first_shard, last_shard)].
    • Skewed shard sizes: If shard S_7 is 10x larger than average, split S_7 virtually into 10 sub-ranges [S_7.0 .. S_7.9] across replicas and include them in the ordered tree. Associativity guarantees an identical result.

    Summary of key trade-offs

    • 4-integer summary (32 B) vs shipping raw shards (1.25 GB): Cuts network transfer by ~40 million times because consecutive 1s decompose cleanly into internal bests, boundary prefixes/suffixes, and all-1 pass-through lengths.
    • Associative but non-commutative merge: Allows arbitrary tree shapes, chunk parallelism, and eager arrival-order neighbour merging, at the cost of carrying [first_shard, last_shard] metadata so order is never flipped.
    • Tree reduction vs central coordinator gather: Central gather is dead simple and fast enough up to a few thousand shards; k-ary tree reduction adds ceil(log_k N) network hops in exchange for horizontal fan-in scaling, rack locality, and O(log N) streaming segment-tree updates.
    • Chunk checkpointing + speculative backups: Uses a few kilobytes of KV writes and occasional extra disk reads on slow replicas to cap tail latency and ensure crashes never trigger full-stream restarts.

Intuition & how it works

Imagine 1,000 people standing shoulder to shoulder in a single line, each holding a long paper strip printed with millions of 0s and 1s. You want to find the longest unbroken streak of 1s if all 1,000 strips were taped end to end. Instead of mailing heavy boxes of paper strips to one coordinator, each person looks at their own strip once and writes just four numbers on an index card: how many total digits their strip has (length), how many 1s touch the left edge (prefix), how many 1s touch the right edge (suffix), and the longest streak seen anywhere on their own strip (best). Any two neighbours can now replace their two index cards with a single combined index card in constant time—and repeat in pairs until one card describes the entire line.

Why do simpler approaches fail? Shipping the raw streams to a single machine transfers terabytes of bits over the network, turning a 1-second parallel disk scan into a 17-minute network bottleneck. On the algorithmic side, having each machine report only its own best misses streaks that cross shard boundaries, and reporting only (prefix, suffix, best) without length breaks whenever a streak starts on Machine 1, runs uninterrupted across an all-1s Machine 2, and continues into Machine 3.

Let's trace our three sample slices: S_1 = [0, 1, 1, 0, 1, 1], S_2 = [1, 1], and S_3 = [1, 0, 1, 1, 1]:

  • Local scan cards (length, prefix, suffix, best): S_1 -> (6, 0, 2, 2), S_2 -> (2, 2, 2, 2), and S_3 -> (5, 1, 3, 3).
  • Merge S_1 and S_2: because S_2 has prefix == length (2 == 2), S_2 has zero 0s! So the combined suffix reaches all the way back into S_1's suffix (2 + 2 = 4), giving (8, 0, 4, 4).
  • Merge (S_1..S_2) with S_3: the boundary bridge joins (S_1..S_2)'s suffix of 4 with S_3's prefix of 1 (4 + 1 = 5), giving final card (13, 0, 3, 5) and global answer 5—matching 0, 1, 1, 0, [1, 1, 1, 1, 1], 0, 1, 1, 1.

Key trade-offs

  • Minimal 4-field summary vs richer metadata: Four 64-bit integers (length, prefix, suffix, best = 32 bytes) are the minimum state required for exactness—dropping prefix/suffix misses boundary runs, and dropping length cannot distinguish [1, 1, 1] from [1, 1, 1, 0, 1, 1, 1]. Adding fields like best_start (starting bit offset) slightly enlarges the struct and merge rules while keeping O(1) message size.
  • Central gather vs hierarchical tree reduction: At N = 1,000 machines, all summaries total ~64 KB, so one coordinator can fold them in microseconds with zero multi-hop complexity. A MapReduce-style reduction tree (where workers compute local summaries in parallel and parent nodes merge child summaries level by level) adds ceil(log_k N) network hops (k = fan-in, the number of child summaries merged per node) in exchange for scaling to 100,000+ shards, keeping traffic rack-local, and supporting O(log N) live updates via a segment tree (a binary tree whose leaves hold shard summaries and internal nodes hold merged ranges).
  • Eager neighbour merging vs strict level barriers: Because the merge operation is associative (grouping adjacent merges in any parenthesization produces the exact same summary), the coordinator can merge any two adjacent finished ranges [a..b] and [b+1..c] as soon as both arrive rather than waiting for the slowest node in each tree level.
  • Chunk checkpointing and speculative backups vs minimal storage/IO: Persisting tiny 64-byte summaries per 64 MB file chunk in a durable key-value store (replicated storage that survives host crashes) and running speculative execution (starting a backup scan on a replica when a slow straggler host exceeds 1.5x median time) costs negligible storage and occasional extra disk reads, but prevents single slow or dead nodes from delaying or restarting the entire job.

Common mistakes

  • Returning only each machine's local maximum, missing runs formed across shard seams (such as [0, 1, 1, 0, 1, 1] + [1, 1, 1, 0, 0], where local maxima are 2 and 3 but the seam bridge is 5).
  • Forgetting the all-1s pass-through case by checking suffix_i + prefix_{i+1} only between immediate pairs without extending prefix and suffix across all-1 shards (prefix == length).
  • Treating merge as commutative (assuming merge(A, B) == merge(B, A)): merging summaries in network arrival order instead of strict shard index order corrupts the stream.
  • Using 32-bit integers for counters: A single 1.25 GB bit-packed shard holds 10^10 bits, overflowing a 32-bit signed integer (max ~2.14 × 10^9); counters must be 64-bit.
  • Breaking on empty shards: An empty shard must equal Summary(0, 0, 0, 0)—an identity element (a neutral value that leaves any other summary unchanged when merged)—which works automatically when the all-1s check is written prefix == length (0 == 0 is true).
  • Asserting associativity by hand-waving instead of stating the clean structural reason: merge(summarize(A), summarize(B)) == summarize(A + B), and sequence concatenation is associative.

Follow-up questions

  • What changes in the local scan or summary merge if the shards hold arbitrary integers instead of bits and we want the longest contiguous streak equal to a given constant K? Nothing changes in Summary or merge! During the local scan on each worker, simply treat each integer x as 1 when x == K and 0 when x != K, then run the exact same 4-integer summary and tree reduction. (If a follow-up instead asks for the longest run of any repeated integer when K is not fixed ahead of time, add first_val and last_val to the summary and allow boundary bridges and all-same-value extensions only when left.last_val == right.first_val, treating empty shards as the identity.)
  • Suppose a worker or intermediate aggregator crashes mid-job; how can the job finish without re-reading every shard across the cluster? Persist every completed RangeSummary—both leaf shards, intra-shard 64 MB chunk checkpoints, and internal tree merges—in a durable key-value store keyed by (job_id, first_shard, last_shard, data_version). If an internal reducer crashes, a replacement reducer reads its two already-saved child summaries and re-runs merge in microseconds with zero disk rescanning; if a worker crashes mid-scan, a replacement worker reads only the uncheckpointed 64 MB chunks from a replicated copy of that single shard. Because summaries are pure functions of immutable shard versions, retries are idempotent (re-saving the same key overwrites an identical value harmlessly).
  • How would you generalize the computation if shards are connected as a directed acyclic graph (DAG) rather than a single linear chain, seeking the longest streak of 1s along any directed path? A DAG (directed acyclic graph) is a network of directed edges with no cycles, where every directed path u_1 -> u_2 -> ... -> u_k represents a valid ordered sequence of shards (for example, branching workflow execution logs) and we want the longest run of 1s along any path. Each worker still scans its own shard once into (length, prefix, suffix, best), and then we propagate values in topological order (an ordering where every predecessor u finishes before any node v it points to): let incoming(v) = max(end(u) for u in predecessors(v)) (or 0 if v has no predecessors), where end(u) is the longest run of 1s touching the very end of u along any path into u. Only the maximum end(u) matters because all incoming streaks extend into the same v.prefix; we set end(v) = incoming(v) + v.length if v is all 1s (v.prefix == v.length) else v.suffix, and take the global maximum of max(v.best, incoming(v) + v.prefix) across all V nodes in O(V + E) merges.

Follow-up questions

Similar questions

More Molocoads interview questions

All 2 Molocoads questions →