DSA AnimatorREVISION VIDEOS
← Back to problems
New

Merge Two Sorted Lists — LeetCode 21 video explanation

Given two sorted linked lists, merge them into one sorted list. Reuse the existing nodes.

Loading videos…

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

Key moments in the Merge Two Sorted Lists video

0:04Problem0:10Example0:15Brute force0:23Key idea0:34Dry run0:51Code1:05Takeaway

What you will learn

Remember: a dummy head makes building a list easy. Always take the smaller head. The video solves Merge Two Sorted Lists (LeetCode 21, Easy) with the Two Pointers Merge pattern from the Linked List topic, and you can replay every step in the interactive Merge Two Sorted Lists animation.

Merge Two Sorted Lists video transcript

Problem

Given two sorted linked lists, merge them into one sorted list. Reuse the existing nodes.

Example

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

Brute force

Collecting all values, sorting them and building a new list costs O of n log n. Both lists are already sorted, so just merge.

Key idea

Start with a dummy node and a tail pointer. Compare the two heads, attach the smaller one to the tail, and advance that list. When one list runs out, attach the rest of the other.

Dry run

1 versus 1, take the first one. Then 2 versus 1, take 1 from the second list. 2 versus 3, take 2, then 4 versus 3, take 3. 4 versus 4, take the first 4, and the second list has one 4 left. Attach it, giving 1, 1, 2, 3, 4, 4.

Code

In code, create a dummy and a tail. While both lists have nodes, link the smaller head to the tail and move forward. Then attach whichever list remains. Return dummy dot next, so it's O of m plus n time and O of 1 space.

Takeaway

Remember: a dummy head makes building a list easy. Always take the smaller head.

More Linked List revision videos

← All 185 DSA revision videos