KatInterview

Unique Union of Several Pre-Sorted Lists

Heaps, Sorting & SearchAuto-graded · 18 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapk-way-mergededuplication

Last 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 lists is 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 k satisfies 0 <= k <= 10^3.
  • The total number of elements N across all inner lists is at most 10^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.