🔥 The Challenge
Problem: Merge two sorted linked lists into one sorted list.
Input: list1 = [1->2->4], list2 = [1->3->4]
Output: [1->1->2->3->4->4]
🧠 My Battle Strategy
I deployed the Two-Pointer Technique with a Dummy Node vanguard:
- Sentinel Node: Created a dummy head to eliminate edge cases.
- Pointer March: Advanced through both lists like shadow soldiers
- Optimal Selection: Always chose the smaller value to maintain order
function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
const dummy = new ListNode(0); // 🛡️ My shield against null cases
let current = dummy;
while (list1 && list2) {
if (list1.val <= list2.val) {
current.next = list1;
list1 = list1.next!;
} else {
current.next = list2;
list2 = list2.next!;
}
current = current.next;
}
current.next = list1 || list2; // ⚡ Finishing move
return dummy.next;
}
💡 Key Insights
Space Efficiency: O(1) space complexity by reusing existing nodes
Time Optimization: O(n+m) time by single-pass merging
Elegant Edge Handling: Dummy node prevents null reference headaches
🚀 Level Up Challenge
Can you solve this recursively? Here's a sneak peek:
function mergeRecursive(l1: ListNode | null, l2: ListNode | null): ListNode | null {
if (!l1) return l2;
if (!l2) return l1;
if (l1.val < l2.val) {
l1.next = mergeRecursive(l1.next, l2);
return l1;
} else {
l2.next = mergeRecursive(l1, l2.next);
return l2;
}
}
Daily Progress: ▰▰▰▰▰ 4.44% (4/90)
Tags: algorithms, linkedlists, typescript, dsa, programming