Unique Union of Several Pre-Sorted Lists
Heaps, Sorting & SearchAuto-graded · 18 test casesLast updated
Combine many ascending integer lists into one ascending list with each distinct value appearing once, ideally using a heap-based k-way merge.
Unique Union of Several Pre-Sorted Lists
You receive a list called lists, where each element is itself a list of integers sorted in ascending order (duplicates may occur within a single list and across different lists).
Return one list that contains every distinct integer found in any of the input lists, with the values arranged in strictly ascending order. Each distinct value must appear exactly once in the result.
Rules
- If
listsis empty, or every inner list is empty, return an empty list. - Inner lists may be empty; they contribute nothing.
- Values may be negative, zero, or positive.
- The result must be a new list of integers in ascending order with no repeated values.
Constraints
- The number of inner lists
ksatisfies0 <= k <= 10^3. - The total number of elements
Nacross all inner lists is at most10^5. - Every inner list is already sorted in ascending (non-decreasing) order.
- Target time complexity:
O(N log k). - Target auxiliary space:
O(k), not counting the returned list.
Examples
Example 1
Input: unique_sorted_union([[1, 3, 5], [2, 3, 6], [1, 5, 7]])
Output: [1, 2, 3, 5, 6, 7]
Example 2
Input: unique_sorted_union([[], [1, 2], [2]])
Output: [1, 2]
Hints
Hint 1
The smallest value not yet consumed is always one of the current front elements of the inner lists. What structure gives you the minimum of k candidates quickly?
Hint 2
Keep one entry per non-empty list in a min-heap, storing the value together with which list it came from and its position. After popping an entry, push the next element from that same list.
Hint 3
Since values leave the heap in non-decreasing order, equal values arrive back to back. Compare each popped value with the last value you appended instead of using a set. Check for an empty result rather than using a sentinel, because values can be negative.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a k-way merge with a deduplication step.
- Put the first element of every non-empty list into a min-heap, as a tuple
(value, list_index, position). - Repeatedly pop the smallest tuple. If the result is empty or its last element differs from the popped value, append the value.
- If the list the value came from has another element, push that next element onto the heap.
- When the heap is empty, return the result.
Why it works
- Heap invariant: the heap always holds the smallest not-yet-processed element of each unfinished list. Because each list is sorted, the heap minimum is the smallest unprocessed element overall.
- Sorted output: values are popped in non-decreasing order, so the output is sorted.
- Deduplication: in a non-decreasing stream, equal values are adjacent, so comparing to the last appended value keeps exactly one copy of each distinct value. Testing
not resultavoids sentinel problems with negative numbers. - Completeness: each element is pushed once and popped once, so every value is examined.
- Tuple ordering: ties on value are broken by the unique list index, so comparisons never fail.
Complexity
- Time:
O(N log k). Each of theNelements is pushed and popped once atO(log k)cost, since the heap holds at mostkentries. - Space:
O(k)auxiliary for the heap, plus the output list.
Reference solution
import heapq
from typing import List
def unique_sorted_union(lists: List[List[int]]) -> List[int]:
heap = []
for list_index, items in enumerate(lists):
if items:
heapq.heappush(heap, (items[0], list_index, 0))
result = []
while heap:
value, list_index, pos = heapq.heappop(heap)
if not result or result[-1] != value:
result.append(value)
nxt = pos + 1
if nxt < len(lists[list_index]):
heapq.heappush(heap, (lists[list_index][nxt], list_index, nxt))
return result