KatInterview

Stream Merging Iterator for Two Ordered Sequences

Data Structure DesignAuto-graded · 22 test cases
MediumAuto-gradedData Structure Designdesign-dsarraysheaps-sorting

Last updated

Simulate a stateful iterator that lazily combines two strictly sorted sequences into a single sorted, duplicate-free stream using constant space.

Design an algorithm that simulates a combined iterator over two input lists, first and second. Both lists are provided in strictly ascending order without internal duplicates.

Your task is to process a sequence of API operation calls given by operations and return a list containing the result of each call in order.

Supported operations in operations:

  • "hasNext": Returns True if there are remaining elements in the combined union, and False otherwise.
  • "next": Returns the next strictly smallest element across both sequences that has not yet been emitted. If both sequences are exhausted and no elements remain, return None.

When an element appears in both input sequences, it must be emitted only once, and the internal pointers for both sequences must advance past that duplicate value simultaneously.

The input sequences hold uniform, comparable types (either all integers or all strings).

Constraints

  • 0 <= len(first), len(second) <= 10^5
  • 1 <= len(operations) <= 10^5
  • Each call in arguments is an empty list [].
  • Elements in first and second are strictly sorted in ascending order.
  • Memory usage should be proportional to the current state ($O(1)$ auxiliary space beyond storing indices).

Examples

Example 1

Input: union_iterator([2, 4, 6, 8, 10], [1, 2, 3, 5, 8, 13], ['hasNext', 'next', 'next', 'next', 'next', 'next', 'next', 'next', 'next', 'next', 'next', 'next', 'hasNext'], [[], [], [], [], [], [], [], [], [], [], [], [], []])

Output: [True, 1, 2, 3, 4, 5, 6, 8, 10, 13, None, None, False]

Example 2

Input: union_iterator(['apple', 'banana', 'orange', 'tree'], ['apple', 'tree', 'zoo'], ['next', 'next', 'hasNext', 'next', 'next', 'next', 'hasNext'], [[], [], [], [], [], [], []])

Output: ['apple', 'banana', True, 'orange', 'tree', 'zoo', False]

Example 3

Input: union_iterator([-10, -9, -5, -1, 0, 2, 4], [-9, -5, -3, -2, 0, 1, 2], ['next', 'next', 'next', 'next', 'next', 'next', 'next', 'next', 'next', 'next', 'next', 'hasNext'], [[], [], [], [], [], [], [], [], [], [], []])

Output: [-10, -9, -5, -3, -2, -1, 0, 1, 2, 4, None, False]

Example 4

Input: union_iterator([1, 2, 3], [], ['hasNext', 'next', 'next', 'hasNext', 'next', 'hasNext', 'next'], [[], [], [], [], [], [], []])

Output: [True, 1, 2, True, 3, False, None]

Hints

Hint 1

Maintain two independent indices/pointers to track the current position in each sequence.

Hint 2

Compare the current elements from both sequences. The smaller element is emitted next, and its index advances.

Hint 3

If elements at both current indices are equal, emit the value once and advance both indices simultaneously.