Merge Two Sorted Linked Lists in DSA Java - Time & Space Complexity
We want to understand how the time needed to merge two sorted linked lists grows as the lists get longer.
The question is: How does the number of steps change when the input lists become bigger?
Analyze the time complexity of the following code snippet.
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode 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 != null) ? l1 : l2;
return dummy.next;
}
This code merges two sorted linked lists into one sorted linked list by comparing nodes one by one.
- Primary operation: The while loop that compares nodes from both lists.
- How many times: It runs until all nodes from both lists are processed, roughly the total number of nodes in both lists combined.
As the total number of nodes increases, the number of comparisons and steps grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 comparisons and moves |
| 100 | About 100 comparisons and moves |
| 1000 | About 1000 comparisons and moves |
Pattern observation: The steps increase directly with the total number of nodes, so doubling the nodes roughly doubles the work.
Time Complexity: O(n + m)
This means the time to merge grows linearly with the total number of nodes in both lists combined.
[X] Wrong: "The merge takes quadratic time because of the nested if inside the loop."
[OK] Correct: The if statement is inside a single loop that moves forward through the lists once, so it does not multiply the steps; it just chooses which node to add next.
Understanding this linear merging process is a key skill for working with linked lists and sorting algorithms, showing you can combine data efficiently.
"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 input lists
Two linked lists are sorted individually, meaning their elements are in ascending order.Step 2: Merge while maintaining order
The goal is to combine these two lists into one sorted list that contains all elements from both.Final Answer:
To create a new sorted linked list containing all elements from both lists -> Option AQuick Check:
Merging sorted lists means combining all elements in order [OK]
- Thinking merge means reversing lists
- Assuming merge removes duplicates
- Confusing merge with finding max element
Solution
Step 1: Identify correct parameter types
The function should accept two linked lists, so parameters must be ListNode types, not primitives or arrays.Step 2: Identify correct return type
The function returns a merged linked list, so return type should be ListNode, not void or int.Final Answer:
public ListNode merge(ListNode l1, ListNode l2) -> Option CQuick Check:
Method with ListNode params and return type is correct [OK]
- Using primitive types instead of ListNode
- Returning void instead of ListNode
- Using arrays instead of linked lists
List 1: 1 -> 3 -> 5 -> null List 2: 2 -> 4 -> 6 -> null
Solution
Step 1: Compare first nodes of both lists
1 (List 1) is less than 2 (List 2), so 1 is first in merged list.Step 2: Continue comparing next nodes
Next compare 3 and 2, 2 is smaller, add 2, then 3 vs 4, add 3, then 5 vs 4, add 4, then 5 vs 6, add 5, finally add 6.Final Answer:
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null -> Option DQuick Check:
Merge keeps ascending order combining both lists [OK]
- Appending one list after the other without sorting
- Reversing order of merged list
- Skipping nodes during merge
public ListNode merge(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
if (l1.val < l2.val) {
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 null, correctly handling empty lists.Step 2: Check recursive merge logic
Compares values, recursively merges next nodes, and returns the smaller node, which is correct.Final Answer:
No error; code correctly merges two sorted linked lists -> Option BQuick Check:
Recursive merge with base cases is correct [OK]
- Forgetting to return merged list
- Incorrect base case handling
- Wrong comparison operator causing order issues
List 1: 1 -> 4 -> 5 -> null List 2: 1 -> 3 -> 4 -> nullAfter merging, what is the correct merged list?
Also, explain why the merged list contains duplicate values.
Solution
Step 1: Merge nodes in ascending order
Compare heads: both 1, add both 1s. Then 4 vs 3, add 3. Then 4 vs 4, add both 4s. Finally add 5.Step 2: Understand duplicates in merged list
Duplicates appear because both lists contain the same values independently; merge keeps all elements without removing duplicates.Final Answer:
1 -> 1 -> 3 -> 4 -> 4 -> 5 -> null -> Option AQuick Check:
Merge keeps all elements including duplicates [OK]
- Removing duplicates during merge
- Appending lists without sorting
- Skipping nodes with same values
Ready to prove it?
Pass the test and this pattern moves unknown
