Stream Merging Iterator for Two Ordered Sequences
Data Structure DesignAuto-graded · 22 test casesLast 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": ReturnsTrueif there are remaining elements in the combined union, andFalseotherwise."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, returnNone.
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^51 <= len(operations) <= 10^5- Each call in
argumentsis an empty list[]. - Elements in
firstandsecondare 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires merging two sorted lists while deduplicating common elements and preserving streaming/lazy behavior with $O(1)$ auxiliary space.
We can solve this using a two-pointer technique:
- Maintain index
ptr1forfirstandptr2forsecond. - For
"hasNext": returnTrueifptr1 < len(first)orptr2 < len(second), elseFalse. - For
"next":- If both pointers are at the end, return
None. - If
ptr1reached the end, consume fromsecond(ptr2 += 1). - If
ptr2reached the end, consume fromfirst(ptr1 += 1). - If
first[ptr1] < second[ptr2], outputfirst[ptr1]and advanceptr1. - If
second[ptr2] < first[ptr1], outputsecond[ptr2]and advanceptr2. - If
first[ptr1] == second[ptr2], output the value once and advance bothptr1andptr2.
- If both pointers are at the end, return
Complexity
- Time Complexity: $O(1)$ amortized time per
hasNextornextoperation. Processing $N$ total operations takes $O(N)$ overall time. - Space Complexity: $O(1)$ auxiliary space (excluding the output array for query results), as only two pointer variables are maintained.
from typing import List, Any
def union_iterator(first: List[Any], second: List[Any], operations: List[str], arguments: List[List]) -> List[Any]:
ptr1 = 0
ptr2 = 0
len1 = len(first)
len2 = len(second)
results = []
for op in operations:
if op == "hasNext":
results.append(ptr1 < len1 or ptr2 < len2)
elif op == "next":
if ptr1 >= len1 and ptr2 >= len2:
results.append(None)
elif ptr1 >= len1:
results.append(second[ptr2])
ptr2 += 1
elif ptr2 >= len2:
results.append(first[ptr1])
ptr1 += 1
elif first[ptr1] < second[ptr2]:
results.append(first[ptr1])
ptr1 += 1
elif second[ptr2] < first[ptr1]:
results.append(second[ptr2])
ptr2 += 1
else:
results.append(first[ptr1])
ptr1 += 1
ptr2 += 1
else:
raise ValueError(f"Unsupported operation: {op}")
return results