Merge Two Sorted Lists
Merge Two Sorted Lists
Section titled “Merge Two Sorted Lists”
Easy
Day 9 • Striver Blind 75
📌 Problem Overview
Section titled “📌 Problem Overview”You are given the heads of two sorted linked lists. Merge them into one sorted list.
Examples & Constraints
Section titled “Examples & Constraints”Example 1:
- Input:
list1 = [1,2,4], list2 = [1,3,4] - Output:
[1,1,2,3,4,4]
Example 2:
- Input:
list1 = [], list2 = [0] - Output:
[0]
Constraints:
0 ≤ list length ≤ 50
💡 Approach & Intuition
Section titled “💡 Approach & Intuition”Tests your ability to merge sorted data — a fundamental divide-and-conquer pattern.
🎯 Pattern Recognition
Section titled “🎯 Pattern Recognition”Pattern: Two-Pointer Merge
Compare elements from both lists using two pointers. Take the smaller one and advance. Use a dummy head.
📊 Step-by-Step Execution (Mermaid Diagram)
Section titled “📊 Step-by-Step Execution (Mermaid Diagram)”graph LR Head["ListNode (Head)"] --> P1["Pointer 1 (curr / slow)"] Head --> P2["Pointer 2 (prev / fast)"] P1 -->|Iterate / Reverse| Next["Next Node"] P2 -->|Traverse 2x| Next Next --> Verdict["Return Modified Head / Result"]🐢 Brute Force Solution
Section titled “🐢 Brute Force Solution”function mergeTwoLists(l1, l2) { const arr=[]; while(l1){arr.push(l1.val);l1=l1.next} while(l2){arr.push(l2.val);l2=l2.next} arr.sort((a,b)=>a-b); const d=new ListNode(); let c=d; for(const v of arr){c.next=new ListNode(v);c=c.next} return d.next; }- Time Complexity:
O((n+m) log(n+m)) - Space Complexity:
O(n+m) - Explanation: Extract values, sort, rebuild.
⚡ Optimized Solution
Section titled “⚡ Optimized Solution”function mergeTwoLists(l1, l2) { const dummy = new ListNode(); let curr = dummy; while (l1 && l2) { if (l1.val <= l2.val) { curr.next = l1; l1 = l1.next; } else { curr.next = l2; l2 = l2.next; } curr = curr.next; } curr.next = l1 || l2; return dummy.next;}- Time Complexity:
O(n+m) - Space Complexity:
O(1) - Explanation: Dummy head + two-pointer merge.
🐾 Step-by-Step Walkthrough
Section titled “🐾 Step-by-Step Walkthrough”- Initialize State: Setup necessary pointers, dynamic programming arrays, or hash maps.
- Iterate & Evaluate: Process the input according to the boundary conditions.
- Update & Return: Compute the optimal answer and return early or at termination.
🎙️ FAANG Interview Pitch
Section titled “🎙️ FAANG Interview Pitch”- Use dummy node to avoid null checks
- Compare and attach smaller element
- Attach remainder when one list ends
💡 Progressive Hints
Section titled “💡 Progressive Hints”- Use a dummy node.
- Compare and attach the smaller node.
- Attach remaining nodes when one list is exhausted.