Merge Two Sorted Linked Lists in DSA C++ - Time & Space Complexity
We want to know how the time to merge two sorted linked lists grows as the lists get longer.
How does the number of steps change when the input size increases?
Analyze the time complexity of the following code snippet.
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (!l1) return l2;
if (!l2) return l1;
if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
This code merges two sorted linked lists by choosing the smaller head each time and recursing on the rest.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing the current nodes of both lists and moving forward.
- How many times: Once for each node in both lists combined, until all nodes are merged.
Each step processes one node from either list, so the total steps grow with the total number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 (total nodes) | About 10 comparisons and moves |
| 100 (total nodes) | About 100 comparisons and moves |
| 1000 (total nodes) | About 1000 comparisons and moves |
Pattern observation: The number of operations grows roughly in a straight line with the total number of nodes.
Time Complexity: O(n + m)
This means the time grows linearly with the total number of nodes in both lists combined.
[X] Wrong: "The time complexity is O(n * m) because we compare nodes multiple times."
[OK] Correct: Each node is visited only once, so comparisons happen at most once per node, not multiplied.
Understanding this linear merging process helps you handle many linked list problems efficiently and shows you can analyze recursive code clearly.
"What if we changed the lists to arrays? How would the time complexity of merging change?"
Practice
Solution
Step 1: Understand the merge operation
Merging means combining two lists into one while keeping the order sorted.Step 2: Maintain sorted order during merge
We pick the smaller node from the heads of both lists repeatedly to keep the merged list sorted.Final Answer:
Combine nodes from both lists maintaining sorted order -> Option CQuick Check:
Merge = Combine sorted lists [OK]
- Trying to reverse lists instead of merging
- Sorting lists again after merging
- Ignoring order and just concatenating
Solution
Step 1: Understand node structure in C++
A node should have data and a pointer to the next node.Step 2: Check pointer usage
Using Node* next is correct to point to the next node; Node next would cause infinite size error.Final Answer:
struct Node { int data; Node* next; }; -> Option DQuick Check:
Node pointer = Node* next [OK]
- Using object instead of pointer for next node
- Missing semicolon after struct
- Using class without access specifier
List1: 1 -> 3 -> 5 -> nullList2: 2 -> 4 -> 6 -> nullUsing a standard merge algorithm?
Solution
Step 1: Compare heads of both lists
Start with 1 (List1) and 2 (List2). 1 is smaller, so first node is 1.Step 2: Continue picking smaller nodes
Next compare 3 and 2, pick 2; then 3 and 4, pick 3; then 5 and 4, pick 4; then 5 and 6, pick 5; finally 6.Final Answer:
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null -> Option AQuick Check:
Sorted merge = 1,2,3,4,5,6 [OK]
- Appending one list after the other without sorting
- Mixing node order incorrectly
- Skipping nodes during merge
Node* merge(Node* l1, Node* l2) {
if (!l1) return l2;
if (!l2) return l1;
if (l1->data < l2->data) {
l1->next = merge(l1->next, l2);
return l1;
} else {
l2->next = merge(l1, l2->next);
return l2;
}
}Solution
Step 1: Check base cases
Code returns the other list if one is empty, which is correct.Step 2: Check recursive merge logic
It compares data correctly and recursively merges the rest, returning the smaller node.Final Answer:
No error, code correctly merges two sorted lists -> Option AQuick Check:
Recursive merge logic correct [OK]
- Forgetting to return merged list
- Wrong base case conditions
- Using wrong pointers in recursion
List1: 1 -> 4 -> 5 -> 7 -> nullList2: 2 -> 3 -> 6 -> 8 -> 9 -> nullWrite the merged list after merging them. Then, if you want to remove duplicates from the merged list, what will be the final list?
Assume duplicates can appear after merge.
Solution
Step 1: Merge both sorted lists
Pick nodes in order: 1,2,3,4,5,6,7,8,9 forming a sorted merged list.Step 2: Remove duplicates if any
Since all values are unique, the list remains the same after removing duplicates.Final Answer:
Merged: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> null; After removing duplicates: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> null -> Option BQuick Check:
Sorted merge with unique values [OK]
- Concatenating lists without sorting
- Assuming duplicates always exist
- Removing nodes incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
