Merge Two Sorted Lists
Problem Statement
Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
Constraints:
- The number of nodes in both lists is in the range [0, 50]
- -100 <= Node.val <= 100
- Both l1 and l2 are sorted in non-decreasing order
Input Format:
- Two linked lists l1 and l2
Output Format:
- The merged sorted linked list
Examples:
Example 1:
Input:
l1 = [1,2,4], l2 = [1,3,4]
Output:
[1,1,2,3,4,4]
Explanation:
The two lists are merged to form a single sorted list.
Example 2:
Input:
l1 = [], l2 = []
Output:
[]
Explanation:
Both lists are empty, so the result is also empty.
Example 3:
Input:
l1 = [], l2 = [0]
Output:
[0]
Explanation:
When one list is empty, the result is the other list.
Solutions
Iterative Approach
Use a dummy head and iterate through both lists, appending the smaller node.
Recursive Approach
Recursively determine which list has the smaller head, and merge the remainder.
Algorithm Walkthrough
Example input:
Step-by-step execution:
- l1 = [1,2,4], l2 = [1,3,4]
- Create dummy = -1, tail = dummy
- While loop iteration 1:
- Compare: 1 <= 1 is true
- tail.next = l1(1), l1 = [2,4], tail = 1
- While loop iteration 2:
- Compare: 2 > 1 is true
- tail.next = l2(1), l2 = [3,4], tail = 1
- While loop iteration 3:
- Compare: 2 <= 3 is true
- tail.next = l1(2), l1 = [4], tail = 2
- While loop iteration 4:
- Compare: 4 > 3 is true
- tail.next = l2(3), l2 = [4], tail = 3
- While loop iteration 5:
- Compare: 4 <= 4 is true
- tail.next = l1(4), l1 = [], tail = 4
- l1 is null, so tail.next = l2 = [4]
- Result: dummy.next = [1,1,2,3,4,4]
Hints
Hint 1
Hint 2
Hint 3
Video Tutorial
Video tutorials can be a great way to understand algorithms visually
Visualization
Visualize the merging process as nodes are selected from each list and appended to the result list.
Key visualization elements:
- current l1 node
- current l2 node
- merged list so far
Implementation Notes
This problem is a classic linked list manipulation problem that tests your understanding of pointers and linked list operations. Both iterative and recursive approaches have their merits, with the iterative approach being more space-efficient.