Merge Two Sorted Lists - Problem
Given the heads of two sorted linked lists list1 and list2, merge them into a single sorted linked list.
The merged list should be constructed by splicing together the nodes from the input lists - don't create new nodes, just rearrange the existing ones. Return the head of the newly merged linked list.
Example:
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
This is a classic linked list problem that tests your understanding of pointer manipulation and merging algorithms. It's the foundation for more complex problems like merging k sorted lists.
Input & Output
example_1.py โ Basic Merge
$
Input:
list1 = [1,2,4], list2 = [1,3,4]
โบ
Output:
[1,1,2,3,4,4]
๐ก Note:
Both lists start with 1, so we take from list1 first. Then we compare 2 vs 1 (from list2), take 1. Continue this process: 2 vs 3 (take 2), 4 vs 3 (take 3), 4 vs 4 (take from list1), then append remaining 4 from list2.
example_2.py โ Empty List
$
Input:
list1 = [], list2 = [0]
โบ
Output:
[0]
๐ก Note:
When one list is empty, we simply return the other list. No comparison needed.
example_3.py โ Both Empty
$
Input:
list1 = [], list2 = []
โบ
Output:
[]
๐ก Note:
When both lists are empty, the result is also an empty list.
Visualization
Tap to expand
Understanding the Visualization
1
Setup
Start with two sorted lines and an empty result line
2
Compare
Look at the first person in each line
3
Choose
Move the shorter person to the result line
4
Repeat
Continue until one line is empty
5
Finish
Move all remaining people from the non-empty line
Key Takeaway
๐ฏ Key Insight: Since both input lists are already sorted, we only need to compare the first elements and choose the smaller one at each step. This gives us O(n+m) time with O(1) space complexity.
Time & Space Complexity
Time Complexity
O(n + m)
Visit each node exactly once where n and m are lengths of the lists
โ Linear Growth
Space Complexity
O(1)
Only uses a constant amount of extra space for pointers
โ Linear Space
Constraints
- The number of nodes in both lists is in the range [0, 50]
- -100 โค Node.val โค 100
-
Both
list1andlist2are sorted in non-decreasing order
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code