Program to merge two sorted list to form larger sorted list in Python

Suppose we have two sorted lists A and B. We have to merge them and form only one sorted list C. The size of lists may be different.

For example, suppose A = [1,2,4,7] and B = [1,3,4,5,6,8], then merged list C will be [1,1,2,3,4,4,5,6,7,8].

Algorithm

We will solve this using the two-pointer technique. The algorithm works as follows ?

  • Initialize an empty result list and two pointers i=0, j=0
  • While both pointers are within bounds:
    • If lst0[i] < lst1[j], append lst0[i] and increment i
    • If lst0[i] > lst1[j], append lst1[j] and increment j
    • If lst0[i] = lst1[j], append both elements and increment both pointers
  • Append remaining elements from both lists
  • Return the merged list

Method 1: Using Two Pointers

This approach compares elements from both lists and builds the result incrementally ?

def merge_sorted_lists(lst0, lst1):
    result = []
    i = 0
    j = 0
    
    # Compare elements from both lists
    while i < len(lst0) and j < len(lst1):
        if lst0[i] < lst1[j]:
            result.append(lst0[i])
            i += 1
        elif lst0[i] > lst1[j]:
            result.append(lst1[j])
            j += 1
        else:  # Equal elements
            result.append(lst0[i])
            result.append(lst1[j])
            i += 1
            j += 1
    
    # Add remaining elements from lst0
    while i < len(lst0):
        result.append(lst0[i])
        i += 1
    
    # Add remaining elements from lst1
    while j < len(lst1):
        result.append(lst1[j])
        j += 1
    
    return result

# Test the function
list1 = [1, 2, 4, 7]
list2 = [1, 3, 4, 5, 6, 8]
merged = merge_sorted_lists(list1, list2)
print("Merged list:", merged)
Merged list: [1, 1, 2, 3, 4, 4, 5, 6, 7, 8]

Method 2: Using Built-in Functions

Python provides a simpler approach using the heapq.merge() function ?

import heapq

def merge_with_heapq(lst0, lst1):
    return list(heapq.merge(lst0, lst1))

# Test the function
list1 = [1, 2, 4, 7]
list2 = [1, 3, 4, 5, 6, 8]
merged = merge_with_heapq(list1, list2)
print("Merged list:", merged)
Merged list: [1, 1, 2, 3, 4, 4, 5, 6, 7, 8]

Method 3: Simple Concatenation and Sort

For small lists, you can simply concatenate and sort ?

def merge_and_sort(lst0, lst1):
    return sorted(lst0 + lst1)

# Test the function
list1 = [1, 2, 4, 7]
list2 = [1, 3, 4, 5, 6, 8]
merged = merge_and_sort(list1, list2)
print("Merged list:", merged)
Merged list: [1, 1, 2, 3, 4, 4, 5, 6, 7, 8]

Comparison

Method Time Complexity Space Complexity Best For
Two Pointers O(m + n) O(m + n) Large sorted lists
heapq.merge() O(m + n) O(m + n) Clean, readable code
Concatenate + Sort O((m + n) log(m + n)) O(m + n) Small lists or unsorted data

Conclusion

The two-pointer approach is most efficient for merging sorted lists with O(m + n) time complexity. Use heapq.merge() for cleaner code or concatenate + sort for simplicity with small datasets.

Updated on: 2026-03-25T10:52:38+05:30

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements