Object-Oriented K-Way Merger for Timestamped Streams
Hard · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
You receive k sequences of timestamped records, where each individual sequence is expected to be ordered by non-decreasing integer timestamp. Design an object-oriented streaming merger and a batch helper that combine all N records across the k sequences into a single globally ordered stream without mutating the caller's lists or comparing payload fields.
Each element is represented by Record(timestamp: int, tag: str, value: float):
- timestamp is the sole sort key (a signed integer tick, which may be negative, zero, or positive).
- tag and value are opaque payload fields carried along unchanged (value may even be NaN).
Implement KWayMerger and merge_records:
- KWayMerger(inputs: List[List[Record]]): initializes the merger over k = len(inputs) sequences without copying all records up front or modifying inputs.
- has_next() -> bool: returns True while at least one record remains unreturned, and False once every input sequence is exhausted.
- next() -> Record: returns the next record in global non-decreasing timestamp order:
- Deterministic tie-breaking: when two or more available records share the exact same timestamp, emit the record from the sequence with the smaller input index i (0 <= i < k); within a single sequence, preserve original index order. Never compare tag or value.
- Exhaustion: if no unreturned record remains, raise IndexError.
- Order validation: right before returning inputs[i][pos], if pos + 1 < len(inputs[i]) and inputs[i][pos + 1].timestamp < inputs[i][pos].timestamp, raise ValueError without advancing or mutating the merger's internal state.
- merge_records(inputs: List[List[Record]]) -> List[Record]: drains a KWayMerger(inputs) instance from start to finish and returns all merged records in a list.
In an interview setting without an automated judge (including C++17 equivalents), pay equal attention to clean separation between comparison keys and carried payloads, explicit ownership and class invariants, and self-contained unit tests.
Examples
Example 1
Input:
inputs = [
[Record(10, "imu", 9.8), Record(25, "imu", 9.7), Record(40, "imu", 9.9)],
[],
[Record(15, "gps", 37.4), Record(25, "gps", 37.5)],
[Record(12, "cam", 1.0)],
]
Output (merge_records(inputs)):
[
Record(10, "imu", 9.8),
Record(12, "cam", 1.0),
Record(15, "gps", 37.4),
Record(25, "imu", 9.7),
Record(25, "gps", 37.5),
Record(40, "imu", 9.9),
]
Walk-through: Sequence 1 is empty and ignored. Timestamps 10, 12, and 15 are emitted in chronological order from sequences 0, 3, and 2. At timestamp 25, sequence 0 ("imu") and sequence 2 ("gps") tie; sequence 0 comes out first because 0 < 2, followed by sequence 2 and finally timestamp 40.
Example 2
Input:
inputs = [
[Record(-5, "z_hi", 99.0), Record(0, "z_lo", 50.0)],
[Record(-5, "a_first", 1.0), Record(0, "a_next", float("nan"))],
]
Streaming calls on merger = KWayMerger(inputs):
merger.next() -> Record(-5, "z_hi", 99.0)
merger.next() -> Record(-5, "a_first", 1.0)
merger.next() -> Record(0, "z_lo", 50.0)
merger.next() -> Record(0, "a_next", nan)
merger.has_next() -> False
merger.next() -> raises IndexError
Walk-through: Even though "z_hi" sorts after "a_first" alphabetically and nan has no numeric ordering, ties at -5 and 0 are broken strictly by sequence index (0 before 1) because payload fields are never inspected. Once all four records have been pulled, has_next() is False and calling next() again raises IndexError.
Example 3
Input:
inputs = [
[Record(10, "s0", 1.0), Record(30, "s1", 2.0), Record(20, "s2", 3.0)],
[Record(15, "t0", 4.0)],
]
Streaming calls on merger = KWayMerger(inputs):
merger.next() -> Record(10, "s0", 1.0)
merger.next() -> Record(15, "t0", 4.0)
merger.next() -> raises ValueError (30 is followed by 20 in inputs[0])
merger.has_next() -> True
Walk-through: The first two calls return timestamps 10 and 15. On the third call, sequence 0's candidate Record(30, "s1", 2.0) is immediately followed in sequence 0 by timestamp 20 < 30, so next() raises ValueError before mutating heap state; Record(30, "s1", 2.0) remains unconsumed and has_next() stays True.
Constraints
0 <= k <= 10^4, wherek = len(inputs).0 <= N <= 10^5, whereNis the total number ofRecordelements across allksequences.- Individual sequence lengths may be zero or heavily skewed (for example, one long sequence alongside many tiny or empty sequences).
-10^18 <= record.timestamp <= 10^18.- Target time complexity is
O(k + N log k)overall (O(log k)pernext()call) withO(k)auxiliary cursor space insideKWayMerger. - The caller's
inputslists must not be mutated.
Step-by-step walkthrough
Restate the problem and state your design assumptions
We are given
kinput sequences of timestamped records, each already sorted in non-decreasing timestamp order, containingNrecords in total. We must design a clean merging class that produces allNrecords in global timestamp order, and write self-contained C++17 tests without relying on an external judge harness.Because the prompt intentionally leaves data ownership, tie-breaking, and error handling open, state your engineering choices clearly before writing a line of code: - Timestamp type: signed 64-bit integer ticks (
std::int64_tin C++,intin Python), such as nanoseconds since an epoch. Floating-point timestamps lose nanosecond precision at large magnitudes (doublehas only ~15–17 decimal digits) and can containNaN, which breaks comparison rules. - Deterministic tie rule: when two records share the exact same timestamp, emit the smallerinput_idxfirst, and within the same input keep original position order. Notice this makes the merge stable — it produces the exact same sequence as concatenatinginputs[0] + inputs[1] + ...and running a stable sort by timestamp. - Interface: pull-based streaming (hasNext()/next()) so callers can process records lazily one by one, plus a conveniencemergeAll()/merge_records()helper built right on top ofnext(). - Unsorted input handling: if an input violates non-decreasing order (next_timestamp < current_timestamp), throw an error immediately without corrupting the merger's state.Because our sandbox executes Python, we build and test the runnable Python
KWayMergerfirst, then write the matching production C++17KWayMergerand its standalone C++17 test binary.Separate ordering keys from carried payloads
Every
Recordcontains two very different kinds of data: 1. The ordering key (timestamp), which governs when the record comes out. 2. The payload (tag,value, or in robotics logs a multi-kilobyte sensor frame), which is merely carried from input to output.Your heap comparator must never touch payload fields, for three reasons: - Performance: copying or comparing large payloads at every heap swap wastes memory bandwidth. - Correctness: payload fields may have no valid total order — for instance, a floating-point
NaNreturnsfalsefor both<and>, and arbitrary structs in Python/C++ may not implement<. - Determinism: letting payloads break timestamp ties silently overrides your stated(input_idx, pos)tie rule.from typing import List, NamedTuple import heapq class Record(NamedTuple): """One input element. The merge orders by `timestamp` only; `tag` and `value` are payload.""" timestamp: int tag: str value: floatAnd in C++17,
Recordis a plain value struct with nooperator<at all (so nobody accidentally compares payloads):using Timestamp = std::int64_t; // e.g., nanoseconds since epoch struct Record { Timestamp timestamp; // compared during merging std::string tag; // payload: moved once, never compared double value; // payload: may even be NaN };Why a min-heap of k cursors beats sorting or scanning
Compare the three natural ways to merge
ksorted sequences containingNtotal records: - Concatenate allNrecords and stable-sort: takesO(N log N)time andO(N)memory up front, ignoring the fact that each input is already sorted and preventing lazynext()streaming. (However, because it is 5 lines of code, it makes the ideal test oracle — a simple, trusted reference implementation used to verify our fast code!) - Linear scan acrosskfront pointers per output: takesO(N * k)comparisons. ForN = 1,000,000andk = 1,000, that is10^9comparisons. - Min-heap ofklightweight cursors: because each input is already sorted, the globally earliest unreturned record must be sitting at the current front of one of thekinputs. Keeping just one small cursor(timestamp, input_idx, pos)per non-empty input inside a min-heap (a binary tree stored in a flat array whose smallest item always sits at index0) finds the minimum inO(1)and updates it inO(log k):Input 0: [(10,"imu"), (25,"imu"), (40,"imu")] <-- pos 0 has timestamp 10 Input 1: [] (empty -> skipped!) Input 2: [(15,"gps"), (25,"gps")] <-- pos 0 has timestamp 15 Input 3: [(12,"cam")] <-- pos 0 has timestamp 12 Min-heap of lightweight cursors (timestamp, input_idx, pos): (10, 0, 0) <-- smallest timestamp sits at heap[0] / \ (12, 3, 0) (15, 2, 0)For
N = 1,000,000andk = 1,000,N * log2(k)is roughly10,000,000steps — 100x fewer operations than scanning allkheads, using onlyO(k)cursor memory!Build the merger state and heap invariant
KWayMergermaintains one crisp class invariant (a rule that holds before and after every method call):self._heapcontains at most one cursor(timestamp, input_idx, pos)for each input0 .. k-1that still has unreturned records, pointing at that input's earliest unreturned record.Look at why the 3-integer tuple
(timestamp, input_idx, pos)works so cleanly: - Python compares tuples left to right: firsttimestamp, theninput_idx. - Because each input has at most one cursor in_heapat any moment, two cursors in_heapnever have the sameinput_idx! Comparison stops atinput_idxand never needs a fourth field. - Within a single input,posadvances0 -> 1 -> 2, so equal timestamps inside the same input come out in original position order automatically.class KWayMerger: """Merge k lists of records, each sorted by non-decreasing timestamp, into one sorted stream. Tie rule: records with equal timestamps come out by input index, then by their position in that input, so the output order is fully deterministic. Ownership: the merger keeps references to the input lists and copies nothing; the caller must not modify them while merging. """ def __init__(self, inputs: List[List[Record]]): self._inputs = inputs # _heap: min-heap of (timestamp, input_idx, pos) cursors, e.g. [(1, 0, 0), (2, 1, 0)]. # Invariant: one cursor per non-exhausted input pointing at its next unreturned record. # Because input_idx is unique across active cursors, ties never fall through to payloads. self._heap = [] for input_idx in range(len(inputs)): if len(inputs[input_idx]) > 0: first_timestamp = inputs[input_idx][0].timestamp self._heap.append((first_timestamp, input_idx, 0)) # Build the initial heap in O(k) time rather than k separate O(log k) pushes. heapq.heapify(self._heap) def has_next(self) -> bool: """True while at least one record has not been returned yet.""" return len(self._heap) > 0Advance safely in next() and trace the example
In
next(), order of operations matters for exception safety: 1. Peek atself._heap[0](timestamp, input_idx, pos) without popping yet. 2. Check ifpos + 1 < len(seq). If that next element hasnext_record.timestamp < timestamp, raiseValueErrorright now — because we have not touchedself._heapyet, the merger remains completely intact! 3. Ifnext_posexists and is valid, callheapq.heapreplace(self._heap, ...)to pop the root and sift the replacement cursor down in oneO(log k)pass instead of two (heappop+heappush). Otherwise, inputinput_idxis exhausted, so callheapq.heappop(self._heap).def next(self) -> Record: if not self._heap: raise IndexError("no records left") # Phase 1: Peek at the earliest cursor without mutating the heap yet. timestamp, input_idx, pos = self._heap[0] seq = self._inputs[input_idx] next_pos = pos + 1 # Phase 2: Validate sorted order before changing heap state (strong exception guarantee) # and advance this input's cursor in a single O(log k) sift. if next_pos < len(seq): next_record = seq[next_pos] if next_record.timestamp < timestamp: raise ValueError(f"input {input_idx} is not sorted at position {next_pos}") heapq.heapreplace(self._heap, (next_record.timestamp, input_idx, next_pos)) else: heapq.heappop(self._heap) return seq[pos]Trace Example 1's 4-channel merge step by step (
input 0: 10 imu, 25 imu, 40 imu;input 1: [];input 2: 15 gps, 25 gps;input 3: 12 cam):Step Heap cursors (ts, in, pos) Action & Emitted Record ----------------------------------------------------------------------------------------- init [(10,0,0), (12,3,0), (15,2,0)] input 1 is empty -> skipped 1 [(12,3,0), (15,2,0), (25,0,1)] pop (10,0,0) -> emit (10,"imu"), push (25,0,1) 2 [(15,2,0), (25,0,1)] pop (12,3,0) -> emit (12,"cam"), input 3 done 3 [(25,0,1), (25,2,1)] pop (15,2,0) -> emit (15,"gps"), push (25,2,1) 4 [(25,2,1), (40,0,2)] tie ts=25: input 0 < 2 -> emit (25,"imu"), push (40,0,2) 5 [(40,0,2)] pop (25,2,1) -> emit (25,"gps"), input 2 done 6 [] pop (40,0,2) -> emit (40,"imu"), heap empty -> stopTranslate the exact design to idiomatic C++17
In C++17, the algorithm is identical, and four language/library details separate a clean senior implementation from buggy code: 1. Reversed comparator (
>):std::priority_queueis a max-heap by default — it puts the element considered "largest" on top! For the earliest timestamp and smallestinput_idxto sit on top, ourComesLaterfunctor must returntruewhenacomes afterb(a.timestamp > b.timestamp, thena.input_idx > b.input_idx). 2. Strict weak ordering: A C++ comparator must returnfalsewhen two items are equal (>never>=); returningtrueon equality causes undefined behavior inside<queue>. 3. O(k) heap construction: Passing a filledstd::vector<Cursor>intostd::priority_queue(ComesLater{}, std::move(initial))invokesstd::make_heaponce inO(k)time instead of doingkseparateO(log k)pushes. 4. Zero-copy ownership andstd::move: Takingstd::vector<std::vector<Record>>by value lets callers move their buffer in (std::move(inputs)). BecauseCursorstores only 24 bytes (three 64-bit integers) and eachposis visited at most once,next()movesseq[top.pos]out withstd::move, andmergeAll()callsout.reserve(remaining_)so growing the output vector never triggers extra reallocations!// kway_merger.h #pragma once #include <cstddef> #include <cstdint> #include <queue> #include <stdexcept> #include <string> #include <utility> #include <vector> using Timestamp = std::int64_t; struct Record { Timestamp timestamp; std::string tag; double value; }; // Merges k timestamp-sorted sequences into one sorted stream. // Tie rule: equal timestamps emit smaller input_idx first, then earlier pos. // Ownership: takes ownership of `inputs` by value and moves each Record out once. class KWayMerger { public: explicit KWayMerger(std::vector<std::vector<Record>> inputs) : inputs_(std::move(inputs)), remaining_(0), heap_(ComesLater{}, buildInitialCursors()) {} bool hasNext() const { return !heap_.empty(); } Record next() { if (heap_.empty()) { throw std::out_of_range("KWayMerger::next: no records left"); } // Copy the 3-integer Cursor BEFORE pop() so we never hold a dangling reference. const Cursor top = heap_.top(); std::vector<Record>& seq = inputs_[top.input_idx]; const std::size_t next_pos = top.pos + 1; // Validate non-decreasing order BEFORE modifying heap_ or moving seq[top.pos]. if (next_pos < seq.size() && seq[next_pos].timestamp < top.timestamp) { throw std::invalid_argument("KWayMerger: input sequence is not sorted by timestamp"); } heap_.pop(); if (next_pos < seq.size()) { heap_.push(Cursor{seq[next_pos].timestamp, top.input_idx, next_pos}); } --remaining_; return std::move(seq[top.pos]); } std::vector<Record> mergeAll() { std::vector<Record> out; out.reserve(remaining_); // Avoid reallocation moves as `out` grows while (hasNext()) { out.push_back(next()); } return out; } private: struct Cursor { Timestamp timestamp; std::size_t input_idx; std::size_t pos; }; // std::priority_queue puts the "largest" item on top, so return true when `a` // should come out LATER than `b` (strictly `>`, never `>=`). struct ComesLater { bool operator()(const Cursor& a, const Cursor& b) const { if (a.timestamp != b.timestamp) { return a.timestamp > b.timestamp; } return a.input_idx > b.input_idx; } }; std::vector<Cursor> buildInitialCursors() { std::vector<Cursor> initial; initial.reserve(inputs_.size()); for (std::size_t i = 0; i < inputs_.size(); ++i) { if (!inputs_[i].empty()) { initial.push_back(Cursor{inputs_[i][0].timestamp, i, 0}); remaining_ += inputs_[i].size(); } } return initial; } std::vector<std::vector<Record>> inputs_; std::size_t remaining_; std::priority_queue<Cursor, std::vector<Cursor>, ComesLater> heap_; };Write self-contained C++17 tests without a judge harness
When there is no online judge, write a 10-line
CHECK(cond)macro that prints__FILE__,__LINE__, and the failed expression and exits with code1(unlikeassert(), which compiles to nothing under-DNDEBUG!). Pair targeted boundary tests (k = 0, all-empty inputs, single input, all-equal timestamps,NaNpayloads, 10,000-vs-1 unbalanced inputs, and exception safety on unsorted input) with 500 seeded random trials checked againstreferenceMerge(concatenating in input order +std::stable_sortby timestamp):// merger_test.cpp // Build & run: clang++ -std=c++17 -Wall -Wextra -Werror -fsanitize=undefined merger_test.cpp -o merger_test && ./merger_test #include "kway_merger.h" #include <algorithm> #include <cmath> #include <cstdlib> #include <iostream> #include <limits> #include <random> #define CHECK(cond) \ do { \ if (!(cond)) { \ std::cerr << __FILE__ << ":" << __LINE__ << ": CHECK failed: " #cond \ << "\n"; \ std::exit(1); \ } \ } while (0) bool operator==(const Record& a, const Record& b) { return a.timestamp == b.timestamp && a.tag == b.tag && a.value == b.value; } bool earlierByTimestamp(const Record& a, const Record& b) { return a.timestamp < b.timestamp; } // Reference oracle: concatenate in input order + stable_sort preserves (input_idx, pos) ties! std::vector<Record> referenceMerge(const std::vector<std::vector<Record>>& inputs) { std::vector<Record> all; for (const std::vector<Record>& seq : inputs) { all.insert(all.end(), seq.begin(), seq.end()); } std::stable_sort(all.begin(), all.end(), earlierByTimestamp); return all; } std::vector<Record> merge(std::vector<std::vector<Record>> inputs) { KWayMerger merger(std::move(inputs)); return merger.mergeAll(); } void testSample1() { std::vector<std::vector<Record>> inputs = { {{10, "imu", 9.8}, {25, "imu", 9.7}, {40, "imu", 9.9}}, {}, {{15, "gps", 37.4}, {25, "gps", 37.5}}, {{12, "cam", 1.0}}, }; std::vector<Record> want = { {10, "imu", 9.8}, {12, "cam", 1.0}, {15, "gps", 37.4}, {25, "imu", 9.7}, {25, "gps", 37.5}, {40, "imu", 9.9}, }; CHECK(merge(inputs) == want); } void testNoInputsAndOnlyEmptyInputs() { CHECK(merge({}).empty()); CHECK(merge({{}, {}, {}}).empty()); KWayMerger merger({}); CHECK(!merger.hasNext()); bool threw = false; try { merger.next(); } catch (const std::out_of_range&) { threw = true; } CHECK(threw); } void testSingleInput() { std::vector<Record> only = {{1, "x", 1.0}, {1, "y", 2.0}, {5, "z", 3.0}}; CHECK(merge({only}) == only); } void testAllEqualTimestampsKeepInputThenPositionOrder() { std::vector<std::vector<Record>> inputs = { {{7, "0:0", 0.0}, {7, "0:1", 0.0}}, {{7, "1:0", 0.0}}, {{7, "2:0", 0.0}, {7, "2:1", 0.0}}, }; std::vector<Record> want = { {7, "0:0", 0.0}, {7, "0:1", 0.0}, {7, "1:0", 0.0}, {7, "2:0", 0.0}, {7, "2:1", 0.0}, }; CHECK(merge(inputs) == want); } void testTieOrderIgnoresPayloadAndNaN() { const double nan_val = std::numeric_limits<double>::quiet_NaN(); std::vector<std::vector<Record>> inputs = { {{5, "z", 9.0}}, {{5, "a", 1.0}}, {{5, "m", nan_val}}, }; std::vector<Record> got = merge(inputs); CHECK(got.size() == 3); CHECK(got[0].tag == "z" && got[1].tag == "a" && got[2].tag == "m"); CHECK(std::isnan(got[2].value)); } void testVeryUnbalancedInputs() { std::vector<std::vector<Record>> inputs(4); for (Timestamp t = 0; t < 10000; ++t) { inputs[0].push_back({t, "big", 0.0}); } inputs[1] = {{-1, "first", 0.0}}; inputs[2] = {{5000, "middle", 0.0}}; inputs[3] = {{20000, "last", 0.0}}; CHECK(merge(inputs) == referenceMerge(inputs)); } void testOutOfOrderInputThrowsWithoutConsuming() { KWayMerger merger({{{1, "a", 0.0}, {5, "b", 0.0}, {3, "c", 0.0}}}); CHECK(merger.next().tag == "a"); for (int attempt = 0; attempt < 2; ++attempt) { bool threw = false; try { merger.next(); } catch (const std::invalid_argument&) { threw = true; } CHECK(threw); CHECK(merger.hasNext()); } } void testRandomAgainstReference() { std::mt19937 rng(42); // Fixed seed guarantees reproducible failures for (int trial = 0; trial < 500; ++trial) { int k = static_cast<int>(rng() % 6); std::vector<std::vector<Record>> inputs(k); for (int i = 0; i < k; ++i) { int length = static_cast<int>(rng() % 8); Timestamp t = static_cast<Timestamp>(rng() % 3); for (int p = 0; p < length; ++p) { t += static_cast<Timestamp>(rng() % 3); // Small steps generate heavy ties inputs[i].push_back({t, std::to_string(i) + ":" + std::to_string(p), 0.0}); } } CHECK(merge(inputs) == referenceMerge(inputs)); } } int main() { testSample1(); testNoInputsAndOnlyEmptyInputs(); testSingleInput(); testAllEqualTimestampsKeepInputThenPositionOrder(); testTieOrderIgnoresPayloadAndNaN(); testVeryUnbalancedInputs(); testOutOfOrderInputThrowsWithoutConsuming(); testRandomAgainstReference(); std::cout << "all tests passed\n"; return 0; }Complete solution
from typing import List, NamedTuple import heapq class Record(NamedTuple): """One input element. The merge orders by `timestamp` only; `tag` and `value` are payload.""" timestamp: int tag: str value: float class KWayMerger: """Merge k lists of records, each sorted by non-decreasing timestamp, into one sorted stream. Tie rule: records with equal timestamps come out by input index, then by their position in that input, so the output order is fully deterministic. Ownership: the merger keeps references to the input lists and copies nothing; the caller must not modify them while merging. """ def __init__(self, inputs: List[List[Record]]): self._inputs = inputs # _heap: min-heap of (timestamp, input_idx, pos) cursors, e.g. [(1, 0, 0), (2, 1, 0)]. # Invariant: one cursor per non-exhausted input pointing at its next unreturned record. # Because input_idx is unique across active cursors, ties never fall through to payloads. self._heap = [] for input_idx in range(len(inputs)): if len(inputs[input_idx]) > 0: first_timestamp = inputs[input_idx][0].timestamp self._heap.append((first_timestamp, input_idx, 0)) # Build the initial heap in O(k) time rather than k separate O(log k) pushes. heapq.heapify(self._heap) def has_next(self) -> bool: """True while at least one record has not been returned yet.""" return len(self._heap) > 0 def next(self) -> Record: """Return the next record in merged order. Raise IndexError if no record is left. Raise ValueError, leaving the merger unchanged, if the record about to be returned is followed in its own input by a smaller timestamp. """ if not self._heap: raise IndexError("no records left") # Phase 1: Peek at the earliest cursor without mutating the heap yet. timestamp, input_idx, pos = self._heap[0] seq = self._inputs[input_idx] next_pos = pos + 1 # Phase 2: Validate sorted order before changing heap state (strong exception guarantee) # and advance this input's cursor in a single O(log k) sift. if next_pos < len(seq): next_record = seq[next_pos] if next_record.timestamp < timestamp: raise ValueError(f"input {input_idx} is not sorted at position {next_pos}") heapq.heapreplace(self._heap, (next_record.timestamp, input_idx, next_pos)) else: heapq.heappop(self._heap) return seq[pos] def merge_records(inputs: List[List[Record]]) -> List[Record]: """Return every record of every input in one list, in the order KWayMerger.next() gives.""" merger = KWayMerger(inputs) merged = [] while merger.has_next(): merged.append(merger.next()) return merged✅ Submit now — all tests should pass.
Intuition & how it works
Picture k airport security lines where travelers inside each line are already standing in order of flight departure time, and a single agent needs to call the next traveler overall. The agent never needs to look partway down any line, because nobody standing behind the front person of line i can have an earlier time than the front person of line i. By keeping just one tiny index card — a cursor (timestamp, input_idx, pos) — for the front person of each non-empty line inside a min-heap (a tree-in-an-array structure that keeps the smallest element at index 0 and updates in logarithmic time), we always pluck the globally earliest record immediately and slide that one line's cursor forward by one spot.
Two obvious approaches fall short here. Dumping all N records into one giant vector and sorting takes O(N log N) time, wastes memory holding everything at once, and cannot yield the first merged record until every input has been copied. Keeping k cursors in a plain list and scanning all k of them to pick each output record takes O(N * k) comparisons — which turns N = 100,000 records across k = 2,000 sensor channels into 200,000,000 comparisons instead of roughly 1,100,000 heap steps.
Walk through a 3-channel merge: input 0 = [(10, "imu"), (25, "imu")], input 1 = [], input 2 = [(25, "gps")]:
1. Skip empty input 1 and heapify the front cursors of inputs 0 and 2: heap = [(10, 0, 0), (25, 2, 0)].
2. next() peeks (10, 0, 0), sees input 0 has (25, "imu") at index 1 (25 >= 10), replaces the root cursor with (25, 0, 1), and returns (10, "imu"); now heap = [(25, 0, 1), (25, 2, 0)].
3. Both remaining cursors tie at timestamp = 25, so input_idx breaks the tie deterministically (0 < 2): next() pops (25, 0, 1) to emit (25, "imu"), and the final next() pops (25, 2, 0) to emit (25, "gps") — without ever comparing "imu" against "gps".
Complexity
- Time — O(k + N log k): Scanning the
kinput headers and building the initial heap withheapq.heapify(orstd::make_heapinsidestd::priority_queue's container constructor in C++) takes linearO(k)time. Each of theNcalls tonext()performs oneO(1)peek, oneO(1)neighbor order check, and oneO(log k)heap replacement or pop on a heap of size at mostk. - Space — O(k) auxiliary memory:
KWayMergerstores at mostkthree-integer cursors in the heap and zero duplicateRecordcopies. Callingmerge_records()/mergeAll()allocates anO(N)output list to hold the returned sequence itself (pre-reserved viaout.reserve(remaining_)in C++ so eachRecordis moved out once with zero reallocation copies).
Edge cases
- Zero inputs (
k = 0) or all-empty inputs ([[], [], []]): Every empty sequence is skipped during initialization, so_heapstarts empty,has_next()isFalse, and callingnext()raisesIndexError(std::out_of_rangein C++). - Single non-empty input (
k = 1):_heapholds a single cursor throughout, and every record is emitted in its exact original order. - Ties within one input and across multiple inputs: Equal timestamps inside one input come out in original index order because its single cursor walks forward (
0 -> 1 -> 2), and equal timestamps across inputs come out in ascendinginput_idxorder. - Uncomparable or
NaNpayloads: Becauseinput_idxis strictly unique among cursors currently in_heap, tuple/cursor comparison always resolves before reaching payload fields, sofloat("nan")values never corrupt ordering. - Unsorted input detection without state corruption:
next()checksseq[pos + 1].timestamp < timestampbefore mutating_heapor movingseq[pos], giving the strong exception guarantee (if an exception is thrown, the object's state is completely unchanged). - Extreme signed 64-bit timestamps: Comparing with
<and>rather than subtractinga.timestamp - b.timestampavoids signed integer overflow when merging negative and large positive timestamps.
Common mistakes
- Inverting heap order in C++
std::priority_queue:std::priority_queueis a max-heap by default (std::less), which puts the latest timestamp on top unless your custom comparator uses>("comes out later"). - Violating strict weak ordering with
>=: A strict weak ordering is a comparison rule where an element is never "less than" itself (comp(x, x)must befalse); writinga.timestamp >= b.timestampreturnstrueon ties and triggers undefined behavior in C++ standard heap algorithms. - Storing full
Recordobjects inside the heap: Sifting swaps whole payloadsO(log k)times per record, and becausestd::priority_queue::top()returnsconst T&, you cannotstd::moveaRecordout oftop()without uglyconst_casthacks — storing lightweight integer cursors avoids both problems cleanly. - Pushing
(timestamp, record)in Python: When two timestamps tie, Python falls back to comparingrecordobjects field by field, breaking yourinput_idxtie rule or raisingTypeErrorif payloads do not support<. - Using
assert()in hand-written C++ test binaries: Standard<cassert>disappears completely when compiled with-DNDEBUGin release builds; always write an explicit check macro or helper that aborts on failure in every build mode. - Keeping a
const Cursor&reference acrossheap_.pop(): Callingpop()overwritesheap_[0], turning a reference returned bytop()into a dangling or mutated reference; copy the tiny 3-integerCursorby value before callingpop().
Alternative approaches
- Concatenate and
std::stable_sort(O(N log N)time,O(N)space): Ignores existing per-input sorting and requires materializing allNrecords before emitting the first one, but takes only a few lines and serves as the gold-standard reference oracle in randomized tests. - Iterative pairwise merging (
O(N log k)time,O(N)scratch space): Merge inputs(0, 1),(2, 3), ... inceil(log2(k))passes usingstd::merge(keeping lower-indexed inputs on the left preserves stability), which has great sequential CPU cache locality when all data already lives in RAM and batch output is acceptable. - Tournament / loser tree (
O(k + N log k)time,O(k)space): A complete binary tree over thekcursors where each internal node caches the loser of a match while the winner advances upward; replacing the global minimum traverses leaf-to-root in exactlyceil(log2(k))comparisons instead of up to2 * log2(k)child-plus-parent comparisons in a binary heap.
Follow-up questions
- Suppose records arrive asynchronously over live network or sensor channels instead of prebuilt lists. How would you redesign the API, and what condition guarantees an item can be emitted in order? Switch from synchronous
next()to a non-blocking push/poll interface:onRecord(input_idx, record),onWatermark(input_idx, min_future_ts),closeInput(input_idx), andpollReady() -> vector<Record>. You cannot emit the heap minimum(t, i)while some other open streamjhas an empty buffer unless streamjhas published a watermarkw_j(a monotonic promise that every future record on streamjwill havetimestamp >= w_j) satisfyingw_j > t(orw_j == twithj > iunder our tie rule) — otherwise streamjmight delivert - 1a moment later! To prevent one stalled sensor from halting the entire merger forever, producers emit periodic heartbeat watermarks, per-stream queues enforce bounded backpressure, and records arriving behind an allowed-lateness cutoff are counted and routed to a late-data channel. - What if a single sequence holds millions of items while all remaining sequences contain only a handful? How can you exploit that skew? Standard
O(N log k)heap merging still works, but if sequence0hasL = 10,000,000records while sequences1..k-1have onlyM = 100records combined, payingO(log k)per element of sequence0wastes heap sifts on long consecutive runs from sequence0. Peek at the second-best cursor in the heap (the smaller ofheap[1]andheap[2]in a 0-indexed binary heap): after popping from sequencei, keep streaming directly from sequenceiin a tight loop (or find the run boundary via exponential search — checking offsets1, 2, 4, 8, ...— followed by binary search, then batch-moving the slice) until sequencei's timestamp reaches that second-best cursor. Because theMrecords in other inputs can split sequence0into at mostM + 1runs, heap operations drop fromO((L + M) log k)toO((M + 1) log k)plusO(L)linear moving. - When merging thousands of channels on a latency-critical path, which bottlenecks appear first and how would you tune memory layout and heap operations? Profile CPU counters (cache misses and branch mispredictions) first, then optimize data layout and comparison count in order of impact: (1) write a custom
replaceTop()sift-down on a flatstd::vector<Cursor>(sincestd::priority_queueforcespop()+push(), doing two heap traversals instead of one) or use a 4-ary heap / loser tree to cut cache misses and halve comparisons; (2) shrinkCursorto 16 bytes (int64_t timestamp,uint32_t input_idx,uint32_t pos) or pack((timestamp - epoch_base) << 16) | input_idxinto a singleuint64_tso each comparison is one CPU register instruction and 4,096 cursors fit inside L1/L2 cache (32–64 KiB); and (3) output indices or move payloads directly into pre-reserved buffers while reading disk/socket inputs in 64 KiB chunks. - How would you generalize the C++ design with templates so callers can merge arbitrary value types using a custom key extractor? Template
KWayMerger<class T, class KeyExtractor, class KeyLess = std::less<>>(constrained with C++20 concepts — compile-time requirements on template types such asstd::invocableandstd::strict_weak_order— if C++20 is available) so callers supplyTand a lightweightKeyExtractorfunctor returning the timestamp or sort key. Cache the extracted key insideCursor{Key key; size_t input_idx; size_t pos;}when pushing onto the heap soKeyExtractorexecutes once per record rather thanO(log k)times during sifts, while keeping theinput_idxtie-breaker encapsulated insideKWayMerger. To generalize beyondstd::vector<std::vector<T>>, template or abstract over an input-cursor concept (empty(),peek(),popNext()) so the exact same merger works overstd::span, file block readers, and network iterators.
Follow-up questions
- Suppose records arrive asynchronously over live network or sensor channels instead of prebuilt lists. How would you redesign the API, and what condition guarantees an item can be emitted in order?
- What if a single sequence holds millions of items while all remaining sequences contain only a handful? How can you exploit that skew?
- When merging thousands of channels on a latency-critical path, which bottlenecks appear first and how would you tune memory layout and heap operations?
- How would you generalize the C++ design with templates so callers can merge arbitrary value types using a custom key extractor?
Similar questions
- Thread-Safe Periodic Task Scheduler
- Concurrent 25 FPS Video Playback Engine
- Lock-Based Concurrency vs. MVCC for Versioned Key-Value Storage
- Buffered 25 FPS Video Playback Over Non-Thread-Safe Calls
- Concurrent Fixed-Frequency Task Scheduler
- Greedy Robot-to-Item Dispatch Across an Obstacle Grid
More Nuro interview questions
- Greedy Robot-to-Item Dispatch Across an Obstacle Grid Medium
- Concurrent 25 FPS Video Playback Engine Hard
- Vertical Axis Symmetry for Point Multisets Hard Pro
- Lock-Based Concurrency vs. MVCC for Versioned Key-Value Storage Hard Pro
- Deduplicated Run Duration Across Overlapping Intervals Easy Pro
- Buffered 25 FPS Video Playback Over Non-Thread-Safe Calls Hard Pro
- Multi-Tenant Webhook Delivery and Fleet Telemetry Pipeline Hard Pro
- DAG Workflow Scheduler for Weekly Autonomous Driving Simulations Medium Pro
- Multi-Tenant Distributed GPU Training Cluster Hard Pro
- End-to-End Project Deep Dive: Architecture, Ownership, and Debugging Hard Pro