Skip to content

Merge K Sorted Runs

Easy#k-way-merge#min-heap~20 min

The mission

Problem

You are given k lists, each sorted in ascending order, and some of them may be empty. Combine them into one ascending list holding every value, duplicates included. Read each list only from the front and keep no more than one waiting value per list at any time.

Examples

Input:  lists = [[1, 4, 5], [1, 3, 4], [2, 6]]
Output: [1, 1, 2, 3, 4, 4, 5, 6]
Input:  lists = [[], [0], []]
Output: [0]
Why:    empty lists simply contribute nothing
Input:  lists = []
Output: []
Why:    edge case, no lists at all

Hints

0 / 3

Target time
O(n log k)
Target space
O(n)

Constraints

  • each of the k lists is sorted ascending
  • some lists may be empty

Stuck on the idea rather than the code? K-Way Merge covers it.

Python 3Ctrl+Enter runs
Custom test case