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_iin 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 is2, ending with two trailing1s)S_2 = [1, 1](every bit in this slice is1, length2)S_3 = [1, 0, 1, 1, 1](begins with one leading1, local longest streak is3)
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-
1slices 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
Nmachines. - 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
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 and1s is split acrossNmachines in a known sequence (S_1followed byS_2, ..., followed byS_N), and we want the exact length of the longest unbroken streak of1s in the combined streamS_1 + S_2 + ... + S_N.Concrete assumptions to agree on first
- Scale:
N = 1,000machines, each holding up to10^10bits (10 billion bits). Stored bit-packed—meaning 8 bits are packed into each byte instead of wasting an entire byte per0or1—each shard is1.25 GB, and the whole stream is1.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 of1s 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. mergemust be associative—meaning grouping merges in different tree shapes, such asmerge(merge(A, B), C)versusmerge(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 TBstream. - Must-handle edge cases: a run bridging two neighbours, a shard made entirely of
1s (allowing a run to start on machinei - 1, pass straight through machinei, and continue into machinei + 1), an empty shard (0bits), andN = 1.
- Scale:
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 msTwo practical insights fall right out of these numbers:
- 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.
- At
N = 1,000, even one coordinator could merge all 64 KB, whereas a hierarchical reduction tree pays off whenNgrows to100,000+shards (avoiding TCP connection storms on one node), when aggregating within each datacenter rack first, or when maintaining live streaming updates inO(log N)merges.
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.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 length2 + 2 = 4. - Adding
prefix(leading1s touching the left edge) andsuffix(trailing1s 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 = 4Without
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! Withlength, a range consists entirely of1s if and only ifprefix == length(which is true exactly when zero0s 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 = 0bit = 1:current_run = 1, prefix = 0, best = 1bit = 1:current_run = 2, prefix = 0, best = 2bit = 0:current_run = 0, prefix = 0, best = 2bit = 1:current_run = 1, prefix = 0, best = 2bit = 1:current_run = 2, prefix = 0, best = 2- Returns
Summary(length=6, prefix=0, suffix=2, best=2).
- If we only store
Merge logic and why it is associative
Now suppose
leftsummarizesS_a..S_bandrightsummarizesS_{b+1}..S_c. How do the four numbers combine forleftfollowed immediately byright?length: Total bits simply add up:left.length + right.length.prefix: Starts at the left edge ofleft. Ifleftis 100%1s (left.prefix == left.length), that leading streak continues unbroken intoright's leading1s (left.length + right.prefix). Otherwise, a0insideleftalready stopped it atleft.prefix.suffix: Ends at the right edge ofright. Symmetrically, ifrightis 100%1s (right.prefix == right.length),rightextendsleft's trailing1s (left.suffix + right.length). Otherwise, it stops atright.suffix.best: Any run in the combined range lies completely insideleft(left.best), completely insideright(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 summarysummarize(A + B)of the concatenated bit sequenceA + B. Since string/list concatenation(A + B) + C == A + (B + C)is associative,mergeis guaranteed to be associative on all valid summaries! Notice also thatEMPTY = (0, 0, 0, 0)satisfies0 == 0(all_ones = True), somerge(EMPTY, X) == Xandmerge(X, EMPTY) == X—makingEMPTYa clean identity element (a neutral value that leaves any summary unchanged when merged).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:
- Dispatch (Map): The coordinator sends
Summarize(job_id, i, data_version)to allNworkers simultaneously. Raw shard bytes never leave local NVMe storage. - 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). - 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 workerW1merges its summary withW2's—which avoids dedicated reducer machines and keeps lower-level merges inside the same datacenter rack. - Return Answer: Once root summary
[1..N]is produced,root.bestis the global longest run of1s.
- Dispatch (Map): The coordinator sends
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_treebelow), every level waits for its slowest pair. Becausemergeis associative, the coordinator does not actually need to wait for rigid tree levels! It can maintain a map of completed contiguous ranges keyed byfirst_shardandlast_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 = 10reducesN = 1,000shards inceil(log_10(1000)) = 3hops instead of 10, andk = 32handlesN = 1,000,000shards in just 4 hops.(Optional extension: if callers also want the global bit offset where the longest run starts, add
best_start: inttoSummary. Onmerge(left, right), a bridging run starts atleft.length - left.suffix, and a winning run insiderightshifts toleft.length + right.best_start. Summary size staysO(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 GBon each worker, we reuse the exact sameSummaryandmergeinside each machine:- Multi-core chunking: Slice the
1.25 GBfile into twenty64 MBchunks. Sixteen CPU threads scan chunks in parallel and persist(shard_index, chunk_index) -> Summaryas checkpoints, then merge the 20 chunk summaries in chunk order0..19. - Byte-table lookup + 64-bit word skipping: Instead of branching on 10 billion individual bits, precompute
Summaryfor all 256 possible byte values (0x00to0xFF). 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 equals0x0000000000000000->(64, 0, 0, 0)or0xFFFFFFFFFFFFFFFF->(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- Multi-core chunking: Slice the
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
Nshards on every bit would waste work.First, appending a single bit to a machine's running summary is just a
mergewith a 1-bit summary inO(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_iupdates, 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 storesmerge(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_2reports a new summary, the coordinator updates leafS_2and recomputes only theceil(log2(N))nodes along the path to the root (10merges forN = 1,000), readingroot.bestinO(1). - Even simpler special case: if only the last active shard
S_Nreceives appends whileS_1..S_{N-1}are sealed historical shards, keep a singlefrozen = Summary(S_1..S_{N-1})and computemerge(frozen, live_S_N).bestin oneO(1)merge!
- Each worker updates its local summary per bit in
Fault tolerance, stragglers, and key trade-offs
Handling failures and slow machines without full recomputation
- Reducer crash: Stateless! Because every leaf and intermediate
RangeSummaryis persisted in the durable KV store, another reducer fetches the two already-saved child summaries and re-runsmergein microseconds—zero shard data is rescanned. - Worker crash mid-scan: Underlying distributed storage (such as HDFS or S3/replicated NVMe) keeps
3xshard replicas. A replacement worker loads the finished64 MBchunk checkpoints for that shard from the KV store, scans only the missing chunks from a healthy replica, and merges chunks0..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.5xthe 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 insummaries[(job_id, first_shard, last_shard)]. - Skewed shard sizes: If shard
S_7is10xlarger than average, splitS_7virtually 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 consecutive1s decompose cleanly into internal bests, boundary prefixes/suffixes, and all-1pass-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 addsceil(log_k N)network hops in exchange for horizontal fan-in scaling, rack locality, andO(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.
- Reducer crash: Stateless! Because every leaf and intermediate
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), andS_3 -> (5, 1, 3, 3). - Merge
S_1andS_2: becauseS_2hasprefix == length(2 == 2),S_2has zero0s! So the combined suffix reaches all the way back intoS_1's suffix (2 + 2 = 4), giving(8, 0, 4, 4). - Merge
(S_1..S_2)withS_3: the boundary bridge joins(S_1..S_2)'s suffix of4withS_3's prefix of1(4 + 1 = 5), giving final card(13, 0, 3, 5)and global answer5—matching0, 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—droppingprefix/suffixmisses boundary runs, and droppinglengthcannot distinguish[1, 1, 1]from[1, 1, 1, 0, 1, 1, 1]. Adding fields likebest_start(starting bit offset) slightly enlarges the struct and merge rules while keepingO(1)message size. - Central gather vs hierarchical tree reduction: At
N = 1,000machines, 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) addsceil(log_k N)network hops (k= fan-in, the number of child summaries merged per node) in exchange for scaling to100,000+shards, keeping traffic rack-local, and supportingO(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 MBfile 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 exceeds1.5xmedian 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 are2and3but the seam bridge is5). - Forgetting the all-
1s pass-through case by checkingsuffix_i + prefix_{i+1}only between immediate pairs without extendingprefixandsuffixacross all-1shards (prefix == length). - Treating
mergeas commutative (assumingmerge(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 GBbit-packed shard holds10^10bits, 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 writtenprefix == length(0 == 0is 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
Summaryormerge! During the local scan on each worker, simply treat each integerxas1whenx == Kand0whenx != 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 whenKis not fixed ahead of time, addfirst_valandlast_valto the summary and allow boundary bridges and all-same-value extensions only whenleft.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-shard64 MBchunk 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-runsmergein microseconds with zero disk rescanning; if a worker crashes mid-scan, a replacement worker reads only the uncheckpointed64 MBchunks 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_krepresents a valid ordered sequence of shards (for example, branching workflow execution logs) and we want the longest run of1s 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 predecessorufinishes before any nodevit points to): letincoming(v) = max(end(u) for u in predecessors(v))(or0ifvhas no predecessors), whereend(u)is the longest run of1s touching the very end ofualong any path intou. Only the maximumend(u)matters because all incoming streaks extend into the samev.prefix; we setend(v) = incoming(v) + v.lengthifvis all1s (v.prefix == v.length) elsev.suffix, and take the global maximum ofmax(v.best, incoming(v) + v.prefix)across allVnodes inO(V + E)merges.
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?
- Suppose a worker or intermediate aggregator crashes mid-job; how can the job finish without re-reading every shard across the cluster?
- 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?
Similar questions
- Longest Contiguous Streak of Ones
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency