Lesson 21 of 86BeginnerPro Interactive Lesson

Merging Two Sorted Linked Lists

Compare the two current heads and append the smaller available value.

Core Intuition & How It Works

Merging two sorted linked lists compares the current heads of both lists and splices the smaller node onto the result tail. Because nodes are relinked in place, the merge runs in O(n + m) time and O(1) extra space.

In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.

Time & Space Complexity

MetricComplexity
Time ComplexityO(n + m)
Space ComplexityO(1)
Topic ChapterChapter 4: Linked Lists
Difficulty LevelBeginner

Key Pattern to Recognize

Attach a dummy head, advance tail along whichever list has the smaller value, and link the remaining non-empty suffix at the end.

Common Pitfalls & Edge Cases

Looping to copy the remaining tail one node at a time instead of linking tail.next = l1 || l2 in O(1).

Real-World & Technical Interview Applications

Linked-list merge sort, k-way sorted stream merging, and database external sort-merge joins.

Unlock the full course

All 86 lessons across 15 chapters

View pricing

Delete account

This permanently deletes your account and ends any Pro access.