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
| Metric | Complexity |
|---|---|
| Time Complexity | O(n + m) |
| Space Complexity | O(1) |
| Topic Chapter | Chapter 4: Linked Lists |
| Difficulty Level | Beginner |
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.