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, where k = len(inputs).
  • 0 <= N <= 10^5, where N is the total number of Record elements across all k sequences.
  • 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) per next() call) with O(k) auxiliary cursor space inside KWayMerger.
  • The caller's inputs lists must not be mutated.

Step-by-step walkthrough

  1. Restate the problem and state your design assumptions

    We are given k input sequences of timestamped records, each already sorted in non-decreasing timestamp order, containing N records in total. We must design a clean merging class that produces all N records 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_t in C++, int in Python), such as nanoseconds since an epoch. Floating-point timestamps lose nanosecond precision at large magnitudes (double has only ~15–17 decimal digits) and can contain NaN, which breaks comparison rules. - Deterministic tie rule: when two records share the exact same timestamp, emit the smaller input_idx first, and within the same input keep original position order. Notice this makes the merge stable — it produces the exact same sequence as concatenating inputs[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 convenience mergeAll() / merge_records() helper built right on top of next(). - 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 KWayMerger first, then write the matching production C++17 KWayMerger and its standalone C++17 test binary.

  2. Separate ordering keys from carried payloads

    Every Record contains 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 NaN returns false for 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: float
    

    And in C++17, Record is a plain value struct with no operator< 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
    };
    
  3. Why a min-heap of k cursors beats sorting or scanning

    Compare the three natural ways to merge k sorted sequences containing N total records: - Concatenate all N records and stable-sort: takes O(N log N) time and O(N) memory up front, ignoring the fact that each input is already sorted and preventing lazy next() 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 across k front pointers per output: takes O(N * k) comparisons. For N = 1,000,000 and k = 1,000, that is 10^9 comparisons. - Min-heap of k lightweight cursors: because each input is already sorted, the globally earliest unreturned record must be sitting at the current front of one of the k inputs. 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 index 0) finds the minimum in O(1) and updates it in O(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,000 and k = 1,000, N * log2(k) is roughly 10,000,000 steps — 100x fewer operations than scanning all k heads, using only O(k) cursor memory!

  4. Build the merger state and heap invariant

    KWayMerger maintains one crisp class invariant (a rule that holds before and after every method call):

    self._heap contains at most one cursor (timestamp, input_idx, pos) for each input 0 .. k-1 that 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: first timestamp, then input_idx. - Because each input has at most one cursor in _heap at any moment, two cursors in _heap never have the same input_idx! Comparison stops at input_idx and never needs a fourth field. - Within a single input, pos advances 0 -> 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) > 0
    
  5. Advance safely in next() and trace the example

    In next(), order of operations matters for exception safety: 1. Peek at self._heap[0] (timestamp, input_idx, pos) without popping yet. 2. Check if pos + 1 < len(seq). If that next element has next_record.timestamp < timestamp, raise ValueError right now — because we have not touched self._heap yet, the merger remains completely intact! 3. If next_pos exists and is valid, call heapq.heapreplace(self._heap, ...) to pop the root and sift the replacement cursor down in one O(log k) pass instead of two (heappop + heappush). Otherwise, input input_idx is exhausted, so call heapq.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 -> stop
    
  6. Translate 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_queue is a max-heap by default — it puts the element considered "largest" on top! For the earliest timestamp and smallest input_idx to sit on top, our ComesLater functor must return true when a comes after b (a.timestamp > b.timestamp, then a.input_idx > b.input_idx). 2. Strict weak ordering: A C++ comparator must return false when two items are equal (> never >=); returning true on equality causes undefined behavior inside <queue>. 3. O(k) heap construction: Passing a filled std::vector<Cursor> into std::priority_queue(ComesLater{}, std::move(initial)) invokes std::make_heap once in O(k) time instead of doing k separate O(log k) pushes. 4. Zero-copy ownership and std::move: Taking std::vector<std::vector<Record>> by value lets callers move their buffer in (std::move(inputs)). Because Cursor stores only 24 bytes (three 64-bit integers) and each pos is visited at most once, next() moves seq[top.pos] out with std::move, and mergeAll() calls out.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_;
    };
    
  7. 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 code 1 (unlike assert(), which compiles to nothing under -DNDEBUG!). Pair targeted boundary tests (k = 0, all-empty inputs, single input, all-equal timestamps, NaN payloads, 10,000-vs-1 unbalanced inputs, and exception safety on unsorted input) with 500 seeded random trials checked against referenceMerge (concatenating in input order + std::stable_sort by 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;
    }
    
  8. 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 k input headers and building the initial heap with heapq.heapify (or std::make_heap inside std::priority_queue's container constructor in C++) takes linear O(k) time. Each of the N calls to next() performs one O(1) peek, one O(1) neighbor order check, and one O(log k) heap replacement or pop on a heap of size at most k.
  • Space — O(k) auxiliary memory: KWayMerger stores at most k three-integer cursors in the heap and zero duplicate Record copies. Calling merge_records() / mergeAll() allocates an O(N) output list to hold the returned sequence itself (pre-reserved via out.reserve(remaining_) in C++ so each Record is 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 _heap starts empty, has_next() is False, and calling next() raises IndexError (std::out_of_range in C++).
  • Single non-empty input (k = 1): _heap holds 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 ascending input_idx order.
  • Uncomparable or NaN payloads: Because input_idx is strictly unique among cursors currently in _heap, tuple/cursor comparison always resolves before reaching payload fields, so float("nan") values never corrupt ordering.
  • Unsorted input detection without state corruption: next() checks seq[pos + 1].timestamp < timestamp before mutating _heap or moving seq[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 subtracting a.timestamp - b.timestamp avoids signed integer overflow when merging negative and large positive timestamps.

Common mistakes

  • Inverting heap order in C++ std::priority_queue: std::priority_queue is 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 be false); writing a.timestamp >= b.timestamp returns true on ties and triggers undefined behavior in C++ standard heap algorithms.
  • Storing full Record objects inside the heap: Sifting swaps whole payloads O(log k) times per record, and because std::priority_queue::top() returns const T&, you cannot std::move a Record out of top() without ugly const_cast hacks — storing lightweight integer cursors avoids both problems cleanly.
  • Pushing (timestamp, record) in Python: When two timestamps tie, Python falls back to comparing record objects field by field, breaking your input_idx tie rule or raising TypeError if payloads do not support <.
  • Using assert() in hand-written C++ test binaries: Standard <cassert> disappears completely when compiled with -DNDEBUG in release builds; always write an explicit check macro or helper that aborts on failure in every build mode.
  • Keeping a const Cursor& reference across heap_.pop(): Calling pop() overwrites heap_[0], turning a reference returned by top() into a dangling or mutated reference; copy the tiny 3-integer Cursor by value before calling pop().

Alternative approaches

  • Concatenate and std::stable_sort (O(N log N) time, O(N) space): Ignores existing per-input sorting and requires materializing all N records 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), ... in ceil(log2(k)) passes using std::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 the k cursors where each internal node caches the loser of a match while the winner advances upward; replacing the global minimum traverses leaf-to-root in exactly ceil(log2(k)) comparisons instead of up to 2 * 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), and pollReady() -> vector<Record>. You cannot emit the heap minimum (t, i) while some other open stream j has an empty buffer unless stream j has published a watermark w_j (a monotonic promise that every future record on stream j will have timestamp >= w_j) satisfying w_j > t (or w_j == t with j > i under our tie rule) — otherwise stream j might deliver t - 1 a 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 sequence 0 has L = 10,000,000 records while sequences 1..k-1 have only M = 100 records combined, paying O(log k) per element of sequence 0 wastes heap sifts on long consecutive runs from sequence 0. Peek at the second-best cursor in the heap (the smaller of heap[1] and heap[2] in a 0-indexed binary heap): after popping from sequence i, keep streaming directly from sequence i in a tight loop (or find the run boundary via exponential search — checking offsets 1, 2, 4, 8, ... — followed by binary search, then batch-moving the slice) until sequence i's timestamp reaches that second-best cursor. Because the M records in other inputs can split sequence 0 into at most M + 1 runs, heap operations drop from O((L + M) log k) to O((M + 1) log k) plus O(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 flat std::vector<Cursor> (since std::priority_queue forces pop() + push(), doing two heap traversals instead of one) or use a 4-ary heap / loser tree to cut cache misses and halve comparisons; (2) shrink Cursor to 16 bytes (int64_t timestamp, uint32_t input_idx, uint32_t pos) or pack ((timestamp - epoch_base) << 16) | input_idx into a single uint64_t so 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 as std::invocable and std::strict_weak_order — if C++20 is available) so callers supply T and a lightweight KeyExtractor functor returning the timestamp or sort key. Cache the extracted key inside Cursor{Key key; size_t input_idx; size_t pos;} when pushing onto the heap so KeyExtractor executes once per record rather than O(log k) times during sifts, while keeping the input_idx tie-breaker encapsulated inside KWayMerger. To generalize beyond std::vector<std::vector<T>>, template or abstract over an input-cursor concept (empty(), peek(), popNext()) so the exact same merger works over std::span, file block readers, and network iterators.

Follow-up questions

Similar questions

More Nuro interview questions

All 29 Nuro questions →