Taro Logo

Merge Two Sorted Lists

Easy
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+31
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.6K views
Topics:
Linked Lists

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.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can either of the input lists be empty (i.e., `null`), and if so, how should I handle that?
  2. What is the expected range of values stored within the linked list nodes, and are they guaranteed to be signed integers?
  3. Should the merged list be constructed by mutating and reusing the existing nodes from `list1` and `list2`, or should I allocate brand new nodes for the result?
  4. How should the merged list handle duplicate values when they appear across both input lists?
  5. Is the length of `list1` guaranteed to be comparable to `list2`, or should I optimize for cases where one list is drastically larger than the other?

Brute Force Solution

Approach

Imagine you have two separate piles of cards, and each pile is already sorted from smallest to largest. The brute force strategy involves gathering all the cards from both piles together into one big mixed pile, and then sorting the whole thing from scratch.

Here's how the algorithm would work step-by-step:

  1. Take all the items from the first sorted list and collect them together in a completely new workspace.
  2. Take all the items from the second sorted list and throw them into that same new workspace, ignoring the fact that they were originally in order.
  3. Mix everything up thoroughly so you are left with one big, unsorted collection of items.
  4. Review the entire collection to find the absolute smallest item hiding inside.
  5. Take that smallest item out and place it as the very first piece of your brand new combined line.
  6. Search through all the remaining items in the collection again to find the next smallest one.
  7. Place that second item right after the first one.
  8. Repeat this process of searching through whatever is left in the collection, finding the smallest remaining piece, and attaching it to the end of your growing line until no items are left anywhere in the workspace.

Code Implementation

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def mergeTwoLists(self, list_node_one, list_node_two):
        unsorted_collection = []

        current_node_one = list_node_one
        while current_node_one is not None:
            unsorted_collection.append(current_node_one.val)
            current_node_one = current_node_one.next

        current_node_two = list_node_two
        while current_node_two is not None:
            unsorted_collection.append(current_node_two.val)
            current_node_two = current_node_two.next

        # Gather all elements from both lists into a single workspace before sorting
        unsorted_collection.sort()

        dummy_head_node = ListNode()
        current_tail_node = dummy_head_node

        # Build a new sorted list by sequentially extracting the smallest elements
        for element_value in unsorted_collection:
            current_tail_node.next = ListNode(element_value)
            current_tail_node = current_tail_node.next

        # Return the newly constructed list starting from the node after dummy head
        return dummy_head_node.next

Big(O) Analysis

Time Complexity
O((n + m)^2) – Letting n be the number of elements in the first list and m be the number of elements in the second list, we first collect all (n + m) items into an unsorted workspace. Then, for each of the (n + m) positions in our final combined line, we repeatedly scan through all remaining unsorted items in the workspace to find the absolute smallest one. This requires searching (n + m) elements for the first pick, (n + m - 1) for the second, and so on. This total work approximates (n + m) * (n + m) / 2 operations, which simplifies to a Big O time complexity of O((n + m)^2).
Space Complexity
O(1) – The brute-force strategy described gathers all items into a new workspace and builds a brand new combined line. However, if implemented in-place by rearranging pointers or if evaluated strictly on auxiliary memory beyond the newly constructed output list, the iterative pointer-manipulation approach requires only a constant number of pointer variables to track our current positions. Because no auxiliary data structures like hash maps or recursive call stacks scale with the input size, the extra memory used remains constant. Thus, the auxiliary space complexity evaluates to O(1) relative to the total number of elements N.

Optimal Solution

Approach

Instead of scrambling everything together and sorting it at the very end, we can build the final sorted list progressively by comparing the front of both lists one step at a time. By always picking the smaller of the two front items and moving forward, we naturally weave them together into a single sorted chain.

Here's how the algorithm would work step-by-step:

  1. Create a placeholder starting point for our new combined list so we have somewhere to anchor our first item.
  2. Look at the very front item of each of the two incoming lists simultaneously.
  3. Compare the two front items and select the smaller one to place next in our combined list.
  4. Advance forward in whichever list donated that smaller item so a new item is now at the front.
  5. Attach this chosen item to the end of our growing combined list.
  6. Repeat the comparison and attachment process until you reach the end of one of the lists.
  7. Once one list runs out of items, simply take whatever is left in the other list and attach it directly to the end of your combined list since it is already sorted.

Code Implementation

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


def merge_two_lists(first_sorted_list, second_sorted_list):
    dummy_start_node = ListNode()
    current_tail_node = dummy_start_node

    # Compare front items to weave lists together in sorted order step-by-step.
    while first_sorted_list is not None and second_sorted_list is not None:

        if first_sorted_list.val <= second_sorted_list.val:
            current_tail_node.next = first_sorted_list
            first_sorted_list = first_sorted_list.next
        else:
            current_tail_node.next = second_sorted_list
            second_sorted_list = second_sorted_list.next

        current_tail_node = current_tail_node.next

    # Attach remaining items since the other list has been completely exhausted.
    if first_sorted_list is not None:
        current_tail_node.next = first_sorted_list
    else:
        current_tail_node.next = second_sorted_list

    return dummy_start_node.next

Big(O) Analysis

Time Complexity
O(n + m) – The cost of this merge operation is driven by stepping through each node of the two input lists sequentially until both are exhausted. As we compare the front items, we advance through the nodes one by one without ever revisiting any of them. Letting n be the length of the first list and m be the length of the second list, the algorithm performs at most n + m steps to weave them together. This linear progression means the total operations scale directly with the combined size of the inputs, simplifying to O(n + m).
Space Complexity
O(1) – The iterative approach relies solely on a few pointers and a dummy placeholder node to anchor the new combined list, meaning no new data structures are created. As the total number of elements N across both input lists grows, the extra memory required remains constant. Therefore, the auxiliary space complexity is O(1) because we only reuse and rearrange the existing nodes in memory.

Edge Cases

Both input lists are completely empty or null
How to Handle:
Returning null immediately avoids null pointer exceptions and correctly outputs an empty merged list.
One of the input lists is empty while the other contains elements
How to Handle:
The algorithm attaches the non-empty list directly to the result, preserving all its remaining nodes.
Lists contain only a single node each
How to Handle:
The comparison correctly links the smaller node to the larger one and terminates without extra iterations.
Lists contain duplicate values across or within lists
How to Handle:
Stable splicing logic ensures nodes with equal values are placed consecutively without overwriting.
Input lists contain negative numbers, zeros, and positive integers
How to Handle:
Standard numerical comparison handles mixed signs correctly since order goes from most negative to positive.
One list is significantly longer or contains all elements smaller than the other list
How to Handle:
An iterative approach processes the remainder in linear time without risking call stack overflow.
Recursive implementation with extremely long linked lists
How to Handle:
Iterative merging with a dummy node should be preferred over recursion to prevent exceeding call stack limits.
Memory management in languages with manual memory control
How to Handle:
Nodes are safely reassigned by reference without allocating new memory, preventing memory leaks.
0/75 completed