HEAP-P5

Merge k sorted lists

Practice 5 of 6Heaps8 tests

The problem

You are given a list of sorted lists. Return one sorted list that holds all their values. Some lists may be empty, and there may be no lists at all.

merge_k([[1, 4, 7], [2, 5, 8], [0, 6]])  ->  [0, 1, 2, 4, 5, 6, 7, 8]
merge_k([[], [3], [1, 2]])               ->  [1, 2, 3]

The heapq module is switched off for this problem: write the heap yourself. A heap is a plain list with sift up and sift down (lessons 1 and 2); you can copy your class from HEAP-P1.

One test passes in numbers that count how often they are compared with <, <=, > or >=. They behave like ordinary numbers otherwise. This is how the tests tell an O(log n) heap step from an O(n) scan, which a timer cannot always do.

Limits

  • Up to 60,000 values in up to 300 lists. Use O(n log k) comparisons for n values in k lists.

Builds on HEAP-5 Top-k and k-way merge.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

8 tests, not run yet
Test results
#TestResultReads · time
1Three listsNot run
2Empty listsNot run
3No listsNot run
4One listNot run
5Different lengthsNot run
6TiesNot run
7ComparisonsNot run
860,000 valuesNot run