BackendML

Merge Two Sorted Lists

Easy2 min read
The Merge Two Sorted Lists problem asks us to merge two sorted singly linked lists into a single sorted linked list while preserving the ordering of the elements.

Problem

Given the heads of two sorted singly linked lists, list1 and list2, merge the two lists into one sorted linked list and return the head of the merged list.

The resulting list should contain all nodes from both lists and should remain sorted in ascending order.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

list1 = [1, 2, 4]
list2 = [1, 3, 4]

Output

[1, 1, 2, 3, 4, 4]

Solution

This solution uses a Two Pointer approach to merge the two sorted linked lists. We maintain two pointers, one for each list, and repeatedly select the node with the smaller value.

A dummy node is used to simplify the process of building the merged list. The current pointer always points to the last node in the merged list.

At each step, we compare list1.val and list2.val. The node with the smaller value is attached to current.next, and its corresponding pointer is moved forward.

When one of the lists becomes empty, all remaining nodes from the other list are already sorted, so we attach the remaining list directly to the merged list.

This approach reuses the existing nodes instead of creating new nodes, resulting in O(1) extra space.
class Solution {

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {

        ListNode dummy = new ListNode(0);
        ListNode current = dummy;

        while (list1 != null && list2 != null) {

            if (list1.val <= list2.val) {
                current.next = list1;
                list1 = list1.next;
            } else {
                current.next = list2;
                list2 = list2.next;
            }

            current = current.next;
        }

        if (list1 != null) {
            current.next = list1;
        } else {
            current.next = list2;
        }

        return dummy.next;
    }
}

Complexity

Each node from both linked lists is processed exactly once, so the time complexity is O(n + m), where n and m are the lengths of the two lists.

The solution uses a few pointers and does not create additional nodes, so the extra space complexity is O(1).

Comments

No comments yet. Ask a question or share what helped.