Google VO Interview Question: Merge Sorted Integer Streams

10 Views
No Comments

Implement a function that merges multiple sorted integer streams into a single sorted list.

interface SortedIntegerStream {int next();      // get the integer from the stream in sorted order (small to large)
    boolean hasNext(); // whether there are integers remaining in the stream}

Example:

// [s1, s2, s3]
public List<Integer> merge(SortedIntegerStream s1, SortedIntegerStream s2) {}
public List<Integer> merge(List<SortedIntegerStream> streams) {}

This problem asks you to merge one or more already sorted integer streams into a single sorted list. The standard solution is a k-way merge using a min-heap: keep the current head value from each stream in the heap, repeatedly extract the smallest one, and then push the next value from the same stream if it exists. This yields an efficient O(N log k) approach, where N is the total number of values and k is the number of streams.

END
 0