Merge Two Sorted Linked Lists in DSA Python - 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.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeTwoLists(l1, l2):
dummy = ListNode()
tail = dummy
while l1 and l2:
if l1.val <= l2.val:
tail.next = l1
l1 = l1.next
else:
tail.next = l2
l2 = l2.next
tail = tail.next
tail.next = l1 or l2
return dummy.next
This code merges two sorted linked lists by repeatedly choosing the smaller head node.
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, so roughly the total number of nodes combined.
As the total number of nodes increases, the steps to merge grow roughly the same amount.
| Input Size (total nodes) | Approx. Operations |
|---|---|
| 10 | About 10 comparisons and moves |
| 100 | About 100 comparisons and moves |
| 1000 | About 1000 comparisons and moves |
Pattern observation: The work grows linearly with the total number of nodes.
Time Complexity: O(n + m)
This means the time grows in direct proportion to the total number of nodes in both lists combined.
[X] Wrong: "Merging two lists takes O(n * m) time because of nested comparisons."
[OK] Correct: The code only compares one node from each list at a time, moving forward without going back, so it never repeats work for the same nodes.
Understanding this linear merging process shows you can handle combining sorted data efficiently, a key skill in many coding problems.
"What if the input lists were stored as arrays instead of linked lists? How would the time complexity change?"
Practice
Solution
Step 1: Understand the merging process
Merging two sorted linked lists means combining them into one list that keeps the sorted order.Step 2: Identify the goal
The goal is to have a new linked list that contains all elements from both lists in sorted order.Final Answer:
To create a new sorted linked list containing all elements from both lists -> Option AQuick Check:
Merging = combine sorted lists [OK]
- Thinking merging reverses lists
- Only finding largest element
- Removing duplicates instead of merging
Solution
Step 1: Initialize dummy and current nodes properly
We create a dummy node with value 0 and set current to dummy to build the merged list.Step 2: Check options for correct syntax
def mergeLists(l1, l2): dummy = ListNode(0) current = dummy correctly creates dummy and current pointing to dummy. def mergeLists(l1, l2): dummy = ListNode(0) current = dummy.next incorrectly sets current = dummy.next which is initially None.Final Answer:
def mergeLists(l1, l2): dummy = ListNode(0) current = dummy -> Option CQuick Check:
Dummy node with value 0 starts merge [OK]
- Setting current to dummy.next
- Swapping dummy and current incorrectly
- Setting dummy to null
Solution
Step 1: Compare nodes from both lists in order
Start with 1 (List 1) and 2 (List 2). 1 is smaller, add 1. Then compare 3 and 2, add 2. Continue comparing and adding smaller nodes.Step 2: Build merged list step-by-step
Merged list becomes 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null after adding all nodes in sorted order.Final Answer:
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null -> Option BQuick Check:
Sorted merge combines nodes in ascending order [OK]
- Appending one list fully before the other
- Mixing node order incorrectly
- Skipping nodes during merge
def mergeLists(l1, l2):
dummy = ListNode(0)
current = dummy
while l1 and l2:
if l1.val < l2.val:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current.next = l1 if l1 else l2
return dummy.nextSolution
Step 1: Check pointer updates inside the loop
After assigning current.next, the current pointer must move forward to current.next to continue building the list.Step 2: Identify missing current update
The code misses 'current = current.next' inside the while loop, causing an infinite loop or incorrect list.Final Answer:
The 'current' pointer is not moved forward inside the loop -> Option AQuick Check:
Move current forward after linking nodes [OK]
- Forgetting to move current pointer
- Returning wrong node
- Not handling empty lists (though not error here)
Solution
Step 1: Understand merging with an empty list
If one list is empty, the merged list is just the non-empty list as it is already sorted.Step 2: Apply to given lists
Since the second list is empty and the first is 0 -> 2 -> 4 -> null, the merged list remains 0 -> 2 -> 4 -> null.Final Answer:
0 -> 2 -> 4 -> null -> Option DQuick Check:
Merging with empty list returns the other list [OK]
- Returning null when one list is empty
- Reversing the non-empty list
- Returning only the first node
Ready to prove it?
Pass the test and this pattern moves unknown
