Rakesh PeddamalluAboutProjectsBlogLeetcode Company WiseContact

Suggested Problems

Leetcode - 21. Merge Two Sorted Lists

Problem Description

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

 

Example 1:

Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]

Example 2:

Input: list1 = [], list2 = []
Output: []

Example 3:

Input: list1 = [], list2 = [0]
Output: [0]

 

Constraints:

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.

Example Test Cases

  • [1,2,4]
  • [1,3,4]
  • []
  • []
  • []
  • [0]

Before diving into Solution go through the hints given in the problem

Solution

Merging Two Sorted Linked Lists: Approach, Complexity, and Code

Merging two sorted linked lists is a common problem in coding interviews and data structure applications. In this blog, we will discuss different approaches, analyze their time and space complexity, and provide an optimized solution.


Problem Statement

Given two sorted linked lists, merge them into a single sorted linked list.

Example

Input:

List1: 1 -> 3 -> 5
List2: 2 -> 4 -> 6

Output:

1 -> 2 -> 3 -> 4 -> 5 -> 6

Approach 1: Recursive Solution

Idea

  • Compare the head nodes of both lists.
  • The smaller node becomes the head of the merged list.
  • Recursively merge the remaining nodes.

Code

1var mergeTwoLists = function(list1, list2) {
2    if (!list1) return list2;
3    if (!list2) return list1;
4    
5    if (list1.val <= list2.val) {
6        list1.next = mergeTwoLists(list1.next, list2);
7        return list1;
8    } else {
9        list2.next = mergeTwoLists(list1, list2.next);
10        return list2;
11    }
12};

Complexity Analysis

  • Time Complexity: O(n + m) (where n and m are the sizes of the two lists)
  • Space Complexity: O(n + m) (due to recursive stack calls)

Approach 2: Iterative Solution (Optimized)

Idea

  • Use a dummy node to simplify list operations.
  • Use a pointer to iterate and merge nodes in-place.
  • Attach any remaining nodes after traversal.

Code

1var mergeTwoLists = function (list1, list2) {
2    let res = new ListNode(0); // Dummy node
3    let pointer = res;
4
5    while (list1 !== null && list2 !== null) {
6        if (list1.val <= list2.val) {
7            pointer.next = list1;
8            list1 = list1.next;
9        } else {
10            pointer.next = list2;
11            list2 = list2.next;
12        }
13        pointer = pointer.next;
14    }
15
16    // Attach the remaining nodes
17    pointer.next = list1 !== null ? list1 : list2;
18    
19    return res.next; // Skip dummy node
20};

Complexity Analysis

  • Time Complexity: O(n + m) (since each node is visited once)
  • Space Complexity: O(1) (no extra space used except pointers)

Comparison of Approaches

ApproachTime ComplexitySpace ComplexityIn-Place
RecursiveO(n + m)O(n + m) (due to recursion)❌ No
IterativeO(n + m)O(1)✅ Yes

Final Thoughts

  • If recursion depth is a concern, prefer the iterative approach.
  • The iterative approach is the most optimized as it avoids extra stack space.
  • Both approaches run in O(n + m) time, which is optimal.

Hope this helps in understanding the problem and its solution! 🚀

Support My Blog ❤️

If this blog helped you, consider a small contribution!

Your support keeps this going! 🚀🙏

Published by: Rakesh Reddy Peddamallu

Top Comments (0)