Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Merge Two Sorted Lists in Python
Merging two sorted lists is a common programming problem where we combine two ordered sequences into a single sorted sequence. Python provides several approaches including recursion, iteration, and built-in methods like heapq.merge().
For example, if A = [1,2,4,7] and B = [1,3,4,5,6,8], the merged result will be [1,1,2,3,4,4,5,6,7,8].
Using Recursion with Linked Lists
The recursive approach works by comparing the first elements of both lists and selecting the smaller one ?
class ListNode:
def __init__(self, data, next=None):
self.val = data
self.next = next
def make_list(elements):
if not elements:
return None
head = ListNode(elements[0])
ptr = head
for element in elements[1:]:
ptr.next = ListNode(element)
ptr = ptr.next
return head
def print_list(head):
result = []
ptr = head
while ptr:
result.append(ptr.val)
ptr = ptr.next
print(result)
def merge_two_lists(l1, l2):
if not l1:
return l2
if not l2:
return l1
if l1.val <= l2.val:
l1.next = merge_two_lists(l1.next, l2)
return l1
else:
l2.next = merge_two_lists(l1, l2.next)
return l2
# Example usage
head1 = make_list([1, 2, 4, 7])
head2 = make_list([1, 3, 4, 5, 6, 8])
merged_head = merge_two_lists(head1, head2)
print_list(merged_head)
[1, 1, 2, 3, 4, 4, 5, 6, 7, 8]
Using Simple List Merging
For regular Python lists, we can use a simpler iterative approach ?
def merge_sorted_lists(list1, list2):
result = []
i, j = 0, 0
while i < len(list1) and j < len(list2):
if list1[i] <= list2[j]:
result.append(list1[i])
i += 1
else:
result.append(list2[j])
j += 1
# Add remaining elements
result.extend(list1[i:])
result.extend(list2[j:])
return result
# Example usage
A = [1, 2, 4, 7]
B = [1, 3, 4, 5, 6, 8]
merged = merge_sorted_lists(A, B)
print(merged)
[1, 1, 2, 3, 4, 4, 5, 6, 7, 8]
Using heapq.merge()
Python's heapq module provides an efficient built-in solution ?
import heapq
def merge_with_heapq(list1, list2):
return list(heapq.merge(list1, list2))
# Example usage
A = [1, 2, 4, 7]
B = [1, 3, 4, 5, 6, 8]
merged = merge_with_heapq(A, B)
print(merged)
[1, 1, 2, 3, 4, 4, 5, 6, 7, 8]
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Recursive (Linked Lists) | O(m + n) | O(m + n) | Linked list structures |
| Iterative (Lists) | O(m + n) | O(m + n) | Simple implementation |
| heapq.merge() | O(m + n) | O(1) | Memory-efficient |
Conclusion
Use heapq.merge() for the most efficient solution with regular lists. For linked lists, recursion provides an elegant approach. The iterative method offers good readability and control over the merging process.
