Merge Two Sorted Lists
easyBlind 75NeetCode 150linked-listtwo-pointers
Problem
Given the heads of two singly linked lists already sorted ascending, splice them into one sorted list and return its head. Reuse the existing nodes.
Examples
Input: 1 -> 2 -> 4 and 1 -> 3 -> 4
Output: 1 -> 1 -> 2 -> 3 -> 4 -> 4
Nodes are interleaved in sorted order.
Constraints
- • 0 <= length of each list <= 50
- • -100 <= node value <= 100
- • Both inputs are sorted ascending
Hints(tap to reveal)
- 1. A dummy head simplifies the splice.
- 2. Always attach the smaller current node next.
Optimal approach(spoiler)
- Create a dummy node and a tail pointer at it.
- Compare the two list heads and append the smaller node to the tail.
- Advance whichever list contributed the node.
- Attach the remaining non-empty list at the end.
- Return dummy.next; O(n + m) time, O(1) space.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor