Merge Two Sorted Lists: Combining Ordered Data Efficiently

Reza Shokrzad
4 min readJun 24, 2024

--

An artistic representation of two sorted linked lists merging into one, depicted as streams of numbers combining in an orderly fashion against a digitally inspired background.
Seamless Integration: Visualizing the Merge of Two Sorted Lists

Welcome back to my blog series where we explore key computer algorithms and tackle common coding problems designed to enhance your problem-solving skills. Today, we’re diving into the “Merge Two Sorted Lists” problem, a fundamental exercise in data structure manipulation, specifically dealing with linked lists. In previous posts, we covered “Two Sum”و “Reverse Integer”, “Palindrome Number”, “Roman to Integer”, “Longest Common Prefix”, and “Valid Parentheses” each providing unique insights into handling arrays and numeric calculations. As we continue, we’ll delve into more complex structures and operations, broadening our understanding and application of algorithms in software development.

About the Problem

Understanding the “Merge Two Sorted Lists” Challenge

The “Merge Two Sorted Lists” problem involves combining two pre-sorted linked lists into a single sorted linked list. The challenge lies in doing this efficiently by utilizing the existing order of the elements, thereby minimizing operations and maintaining sorting throughout the process.

Diagram showing the process of merging two sorted linked lists into one sorted list, with list one containing nodes 1, 2, 4 and list two containing nodes 1, 3, 4, resulting in a merged list of nodes 1, 1, 2, 3, 4, 4.
Efficient Merging of Linked Lists: A Visual Guide

Example 1:

  • Input: list1 = [1,2,4], list2 = [1,3,4]
  • Output: [1,1,2,3,4,4]
  • Explanation: The elements from both lists are merged in such a way that the resulting list maintains the non-decreasing order of the elements.

Example 2:

  • Input: list1 = [], list2 = []
  • Output: []
  • Explanation: Both lists are empty, so the merged list is also empty.

Example 3:

  • Input: list1 = [], list2 = [0]
  • Output: [0]
  • Explanation: Since list1 is empty, the merged list is simply list2.

This problem is a classic example used to demonstrate the manipulation and merging of data structures, particularly linked lists, in a way that requires careful consideration of element order and pointer manipulation.

Solutions for “Merge Two Sorted Lists”

1. Simplest Solution: Iterative Approach

This method uses a straightforward iterative approach to compare the heads of the two lists and append the smaller node to the merged list.

class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next

def mergeTwoLists(list1, list2):
# Create a dummy node which will help in forming the new list
dummy = ListNode()
tail = dummy

# Traverse through both lists
while list1 and list2:
if list1.val < list2.val:
tail.next = list1
list1 = list1.next
else:
tail.next = list2
list2 = list2.next
tail = tail.next

# Directly connect the remaining part of list1 or list2
tail.next = list1 if list1 else list2

return dummy.next

2. Optimized Solution: Recursive Approach

The recursive solution simplifies the code and reduces the overhead of iterative condition checks, making the code cleaner and potentially easier to understand.

def mergeTwoLists_recursive(list1, list2):
if not list1:
return list2
if not list2:
return list1

if list1.val < list2.val:
list1.next = mergeTwoLists_recursive(list1.next, list2)
return list1
else:
list2.next = mergeTwoLists_recursive(list2.next, list1)
return list2

Time and Memory Complexity

Iterative Approach:

  • Time Complexity: O(n+m) where nnn and mmm are the lengths of the two lists. Each element in each list is visited once.
  • Space Complexity: O(1) as no additional space is used besides pointers.

Recursive Approach:

  • Time Complexity: O(n+m) similar to the iterative approach because each element is visited once.
  • Space Complexity: O(n+m) in the worst case due to recursion stack space, especially in scenarios where the lists are unbalanced.

Explanation of the Iterative Method

The iterative method to merge two sorted lists involves comparing the current nodes of both lists and attaching the smaller node to the new list’s next pointer. This process continues until one of the lists is exhausted, at which point the remaining list is appended to the result list. This method is efficient and straightforward, leveraging the sorted properties of the lists to minimize operations and achieve optimal time complexity.

Conclusion

Merging two sorted lists is a fundamental problem that showcases the efficiency of basic data structures like linked lists. Both the iterative and recursive methods provide robust solutions, each with its own advantages in terms of simplicity and coding style preferences. The iterative method offers optimal space usage, while the recursive method offers clarity and less code. Understanding these solutions not only reinforces concepts around linked lists but also improves problem-solving skills in handling similar data structure manipulations in more complex scenarios.

Visit my GitHub repository for code snippets and more

This exploration not only prepares us for interviews but also sharpens our problem-solving skills in developing efficient and effective software solutions.

--

--