DSA AnimatorREVISION VIDEOS
← Back to problems
New

Merge K Sorted Lists — LeetCode 23 video explanation

You are given k sorted linked lists. Merge them all into one sorted list.

Loading videos…

DSA Animator › DSA Revision › Linked List › Merge K Sorted Lists

Key moments in the Merge K Sorted Lists video

0:04Problem0:08Example0:16Brute force0:24Key idea0:34Dry run0:50Code1:03Takeaway

What you will learn

Remember: a heap of size k holds one candidate from each list. Each pop gives the next smallest node. The video solves Merge K Sorted Lists (LeetCode 23, Hard) with the Heap Merge pattern from the Linked List topic, and you can replay every step in the interactive Merge K Sorted Lists animation.

Merge K Sorted Lists video transcript

Problem

You are given k sorted linked lists. Merge them all into one sorted list.

Example

For 1, 4, 5 and 1, 3, 4 and 2, 6, the result is 1, 1, 2, 3, 4, 4, 5, 6.

Brute force

Merging the lists one by one into the result costs O of k times n in total. A min heap always knows the smallest head.

Key idea

Put the head of each list into a min heap. Pop the smallest node, attach it to the result, and push its next node if it exists. Repeat until the heap is empty.

Dry run

The heap starts with 1, 1 and 2. Pop 1 from the first list and push 4, then pop 1 from the second list and push 3. Pop 2 and push 6, then pop 3 and push 4. Pop 4, 4, 5 and 6. The result is 1, 1, 2, 3, 4, 4, 5, 6.

Code

In code, a priority queue orders nodes by value. Add every non-null head. While it is not empty, poll a node, link it to the tail, and offer its next. It's O of n log k time and O of k space.

Takeaway

Remember: a heap of size k holds one candidate from each list. Each pop gives the next smallest node.

More Linked List revision videos

← All 185 DSA revision videos