DSA Factory
Free Heaps lessonsHeaps · Stage 2 · Merging streams · Step 1

Merge many sorted lists

Combine k sorted lists into one sorted list by keeping the front value of each list in a min-heap and always taking the smallest. About 16 minutes.

One candidate per list

You have k lists, each sorted. The overall smallest unused value must be at the front of one of them. So keep the front value of every list in a min-heap. The top of the heap is the next value of the merged output.

A heap entry must remember where it came from: the value, which list it belongs to, and its position in that list.

Heap: holds the front value of each list.
Entry: value, list number, position.
In code
heap = []
heapq.heappush(heap, (lst[0], i, 0))
# value, which list, position
Merge the lists 2, 5 and 1, 3, 6 and 4.
1
0
2
1
3
2
4
3
5
4
6
5
i

The fronts are 2, 1 and 4. Take 1 from the second list. It now shows 3.

Move 1 of 5

Replace what you took

Take the smallest entry off the heap and add its value to the output. Its list now has a new front, the value at the next position, if there is one. Push that into the heap.

Repeat until the heap is empty. Empty lists never enter the heap. The output has all the values in order, and the heap never holds more than k entries.

Pop the smallest: add it to the output.
Push the next: from the same list, if any.
In code
nxt = lists[i][pos + 1]
# the next from the same list
Quick check

After taking a value from a list, what goes into the heap?

  1. AThe next value from the same list, if there is one
  2. BAll the remaining values of that list
  3. CNothing
Show the answer

The next value from the same list, if there is one. That list's front has changed, so its new front becomes a candidate.

Your problem

Merge k sorted lists

You are given an array lists of k arrays, each sorted in non-decreasing order. Merge all of them into a single sorted array and return it. Some of the arrays may be empty.

Example
lists = [[1, 4, 5], [1, 3, 4], [2, 6]] → [1, 1, 2, 3, 4, 4, 5, 6]

0 ≤ k ≤ 1,000 · 0 ≤ total number of values ≤ 3,000 · -10,000 ≤ value ≤ 10,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve