Design an Iterator That Merges K Sorted Lists into One Sorted Stream
Company: MongoDB
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design an iterator that takes multiple sorted lists of integers as input and merges them into a single sorted stream of elements.
The iterator should efficiently determine the next smallest element across all input lists using a min-heap (priority queue). When multiple lists contain the same value, elements from the list with the smaller index should appear first.
Implement the `KWayMergeIterator` class that is initialized with a list of sorted integer lists and supports retrieving elements one at a time in non-decreasing order.
Implement the following methods:
- `next() -> int`: returns the next smallest element from the merged sorted stream. It is only called when `hasNext()` returns `True`.
- `hasNext() -> bool`: returns `True` if there are still elements remaining in the merged stream, `False` otherwise.
In the first example, three lists interleave:
```text
Input:
["KWayMergeIterator", "hasNext", "next", "next", "next", "hasNext", "next", "next", "next", "hasNext"]
[[[[1, 4, 7], [2, 5, 8], [3, 6, 9]]], [], [], [], [], [], [], [], [], []]
Output: [null, true, 1, 2, 3, true, 4, 5, 6, true]
Explanation:
iter = KWayMergeIterator([[1, 4, 7], [2, 5, 8], [3, 6, 9]]) # 3 sorted lists
iter.hasNext() # -> True (heap has elements from all 3 lists)
iter.next() # -> 1 (smallest across all lists, from list 0)
iter.next() # -> 2 (from list 1)
iter.next() # -> 3 (from list 2)
iter.hasNext() # -> True (6 elements remain)
iter.next() # -> 4 (from list 0)
iter.next() # -> 5 (from list 1)
iter.next() # -> 6 (from list 2)
iter.hasNext() # -> True (3 elements remain: 7, 8, 9)
```
In the second example, one input list is empty:
```text
Input:
["KWayMergeIterator", "hasNext", "next", "next", "hasNext", "next", "hasNext"]
[[[[1, 3], [], [2]]], [], [], [], [], [], []]
Output: [null, true, 1, 2, true, 3, false]
Explanation:
iter = KWayMergeIterator([[1, 3], [], [2]]) # 3 lists, one empty
iter.hasNext() # -> True (elements remain)
iter.next() # -> 1 (smallest element)
iter.next() # -> 2 (from list 2)
iter.hasNext() # -> True (one element remains: 3)
iter.next() # -> 3 (last element, from list 0)
iter.hasNext() # -> False (all elements exhausted)
```
```hint What each heap entry carries
The heap never needs more than one entry per input list. Decide what an entry must hold so that `next()` can find the following element of the same list, and so that equal values come out in list-index order.
```
```hint Empty inputs
Some lists may be empty, and `k` itself may be 0. Check what your constructor does in both cases.
```
### Constraints & Assumptions
- `0 <= k <= 100`, where `k` is the number of input sorted lists.
- Each input list is sorted in non-decreasing order.
- Elements are integers in the range `-10^5 <= element <= 10^5`.
- The total number of elements across all lists is at most `10^5`.
- `next()` will not be called when `hasNext()` returns `False`.
### Clarifying Questions to Ask
- May the caller modify the input lists after the iterator is built, or can the iterator keep references to them without copying?
- Will the inputs always be in-memory lists, or could they be iterators or streams of unknown length?
- If `next()` is called on an exhausted iterator anyway, should it raise an error or return a sentinel?
### What a Strong Answer Covers
- What each heap entry stores and how ties between equal values are broken.
- How the heap is seeded, how empty lists are handled, and how large the heap can grow.
- How `next()` advances the source list, and why `hasNext()` must not change state.
- The cost of construction, of each `next()` and `hasNext()` call, and the extra space, stated in terms of `k` and the total element count.
### Follow-up Questions
- How would the design change if each input were an iterator of unknown length instead of a list?
- How would you add a `peek()` method that returns the next value without consuming it?
- How would you return each distinct value only once?
- When `k` is 2, is a heap still the right tool, and what would you use instead?
Overview: Design an iterator with next and hasNext that merges k sorted integer lists into one sorted stream, returning equal values in list-index order. It tests min-heap usage, what each heap entry must store, tie-breaking, empty inputs, and per-call time and space complexity.
Community answers
Answer by jobs.souvik.das
class Node implements Comparable {
int value;
final int listIdx;
final Iterator iterator;
Node(int value, int listIdx, Iterator iterator) {
this.value = value;
this.listIdx = listIdx;
this.iterator = iterator;
}
@Override
public int compareTo(Node other) {
// For equal values, prioritize the smaller list index.
if (value == other.value) {
return Integer.compare(listIdx, other.listIdx);
}
return Integer.compare(value, other.value);
}
}
class KWayMergeIterator {
private final PriorityQueue minHeap;
public KWayMergeIterator(List> lists) {
List nodes = new ArrayList<>();
int listIdx = 0;
// Maintain only one candidate from each non-empty list.
for (List list : lists) {
Iterator iterator = list.iterator();
if (iterator.hasNext()) {
nodes.add(
new Node(iterator.next(), listIdx, iterator));
}
++listIdx;
}
// Bottom-up heapify instead of k individual insertions.
minHeap = new PriorityQueue<>(nodes);
}
public boolean hasNext() {
return !minHeap.isEmpty();
}
public int next() {
Node node = minHeap.remove();
int result = node.value;
// Replenish only the source list whose element was consumed.
// Update the node outside the heap to preserve heap ordering.
if (node.iterator.hasNext()) {
node.value = node.iterator.next();
minHeap.offer(node);
}
return result;
}
}
// TC:
// Constructor : O(k)
// next() : O(log k)
// hasNext() : O(1)
//
// SC: O(k)