Merge Two Sorted Linked Lists in DSA Javascript - Time & Space Complexity
When merging two sorted linked lists, we want to know how the time needed grows as the lists get longer.
We ask: How many steps does it take to combine both lists into one sorted list?
Analyze the time complexity of the following code snippet.
function mergeTwoLists(l1, l2) {
let dummy = { val: 0, next: null };
let current = dummy;
while (l1 !== null && l2 !== null) {
if (l1.val <= l2.val) {
current.next = l1;
l1 = l1.next;
} else {
current.next = l2;
l2 = l2.next;
}
current = current.next;
}
current.next = l1 || l2;
return dummy.next;
}
This code merges two sorted linked lists by comparing nodes one by one and linking them in order.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that compares nodes from both lists.
- How many times: It runs until all nodes from both lists are processed, up to the total number of nodes.
As the total number of nodes increases, the number of steps grows roughly the same amount.
| Input Size (total nodes) | Approx. Operations |
|---|---|
| 10 | About 10 comparisons and links |
| 100 | About 100 comparisons and links |
| 1000 | About 1000 comparisons and links |
Pattern observation: The steps increase linearly with the total number of nodes.
Time Complexity: O(n + m)
This means the time grows directly with the sum of the lengths of both lists.
[X] Wrong: "The time complexity is O(n * m) because we compare every node in one list to every node in the other."
[OK] Correct: The code only moves forward through each list once, so each node is visited once, not repeatedly compared to all nodes in the other list.
Understanding this merge process helps you handle linked list problems efficiently, a common skill interviewers look for.
"What if the input lists were not sorted? How would the time complexity change if we still tried to merge them this way?"
Practice
Solution
Step 1: Understand the merging process
Merging means combining two lists into one while keeping the order sorted.Step 2: Identify the goal of merging sorted lists
The goal is to create a new sorted list that contains all elements from both lists without changing their order.Final Answer:
To create a new sorted linked list containing all elements from both lists -> Option CQuick Check:
Merging = combining sorted lists [OK]
- Thinking merging reverses the lists
- Confusing merging with finding max element
- Assuming duplicates are removed automatically
Solution
Step 1: Initialize a dummy node correctly
We create a dummy node with a value (usually 0) to start the merged list.Step 2: Set a pointer to track the current node
We set current to dummy to build the merged list from dummy onwards.Final Answer:
let dummy = new ListNode(0); let current = dummy; -> Option AQuick Check:
Dummy node initialization = let dummy = new ListNode(0); let current = dummy; [OK]
- Using primitive 0 instead of ListNode object
- Swapping dummy and current incorrectly
- Setting current or dummy to null initially
function ListNode(val, next = null) { this.val = val; this.next = next; }
let l1 = new ListNode(1, new ListNode(3, new ListNode(5)));
let l2 = new ListNode(2, new ListNode(4, new ListNode(6)));
function mergeTwoLists(l1, l2) {
let dummy = new ListNode(0);
let current = dummy;
while (l1 && l2) {
if (l1.val < l2.val) {
current.next = l1;
l1 = l1.next;
} else {
current.next = l2;
l2 = l2.next;
}
current = current.next;
}
current.next = l1 || l2;
return dummy.next;
}
let merged = mergeTwoLists(l1, l2);
let result = [];
while (merged) {
result.push(merged.val);
merged = merged.next;
}
console.log(result);Solution
Step 1: Trace the merging loop
Compare nodes: 1 < 2, add 1; 3 > 2, add 2; 3 < 4, add 3; 5 > 4, add 4; 5 < 6, add 5; then add remaining 6.Step 2: Collect merged list values
The merged list values in order are [1, 2, 3, 4, 5, 6].Final Answer:
[1, 2, 3, 4, 5, 6] -> Option BQuick Check:
Sorted merge result = [1, 2, 3, 4, 5, 6] [OK]
- Appending entire list instead of node by node
- Not updating current pointer after adding node
- Mixing order of nodes in merged list
function mergeTwoLists(l1, l2) {
let dummy = new ListNode(0);
let current = dummy;
while (l1 !== null || l2 !== null) {
if (l1.val < l2.val) {
current.next = l1;
l1 = l1.next;
} else {
current.next = l2;
l2 = l2.next;
}
current = current.next;
}
return dummy.next;
}Solution
Step 1: Analyze the while loop condition
The loop uses '||' which allows l1 or l2 to be null, causing errors when accessing val.Step 2: Fix the loop condition
Changing the condition to 'while (l1 && l2)' ensures both lists have nodes before accessing val.Final Answer:
Change while condition to 'while (l1 && l2)' -> Option DQuick Check:
Loop condition with && prevents null pointer errors [OK]
- Using || instead of && in loop condition without null checks
- Forgetting to move current pointer
- Initializing dummy with wrong value type
1 -> 2 -> 3 -> null, what is the merged list?Solution
Step 1: Understand merging with an empty list
If one list is empty, the merged list is just the other list unchanged.Step 2: Apply this to given lists
Since one list is empty and the other is 1 -> 2 -> 3 -> null, the merged list is 1 -> 2 -> 3 -> null.Final Answer:
1 -> 2 -> 3 -> null -> Option AQuick Check:
Merging with empty list returns the non-empty list [OK]
- Assuming error occurs when one list is empty
- Reversing the non-empty list mistakenly
- Returning null instead of the non-empty list
Ready to prove it?
Pass the test and this pattern moves unknown
