Merge Two Sorted Lists - Problem

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

Input & Output

Example 1 — Basic Merge
$ Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
💡 Note: Merge by comparison: 1≤1 (choose list1), 2<3 (choose list1), 3<4 (choose list2), 4≤4 (choose list1), then 4 from list2
Example 2 — One Empty List
$ Input: list1 = [], list2 = [0]
Output: [0]
💡 Note: When one list is empty, return the other list directly
Example 3 — Both Empty
$ Input: list1 = [], list2 = []
Output: []
💡 Note: When both lists are empty, return empty list

Constraints

  • The number of nodes in both lists is in the range [0, 50].
  • -100 ≤ Node.val ≤ 100
  • Both list1 and list2 are sorted in non-decreasing order.

Visualization

Tap to expand
Merge Two Sorted Lists INPUT list1 1 2 4 null list2 1 3 4 null list1 = [1, 2, 4] list2 = [1, 3, 4] Both lists are sorted Two Pointers: p1, p2 p1 p2 ALGORITHM STEPS 1 Create Dummy Node Start with dummy head 2 Compare Values Compare p1.val vs p2.val 3 Append Smaller Link smaller node, move ptr 4 Append Remaining Link remaining nodes Comparison Flow: 1 vs 1 --> take 1 (list1) 2 vs 1 --> take 1 (list2) 2 vs 3 --> take 2 (list1) 4 vs 3 --> take 3 (list2) 4 vs 4 --> take 4, append 4 FINAL RESULT Merged Linked List 1 1 2 3 4 4 null Output: [1, 1, 2, 3, 4, 4] OK - Sorted! Legend: from list1 from list2 Key Insight: Use a dummy node to simplify edge cases. Compare nodes from both lists using two pointers, always appending the smaller value. When one list is exhausted, append the remaining nodes. Time: O(n+m) | Space: O(1) - Only pointer manipulation, no extra space needed. TutorialsPoint - Merge Two Sorted Lists | Two Pointers Merge Approach
Asked in
Amazon 87 Microsoft 45 Apple 32 Google 28
180.3K Views
Very High Frequency
~15 min Avg. Time
8.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen