Sweaty Imposter

Merge Two Sorted Lists

EasyLinked ListBlind 75JuniorOpen on LeetCodeUpdated

You're given the heads of two singly linked lists, list1 and list2, each already sorted in non-decreasing order. Combine them into a single sorted list by linking together the existing nodes rather than creating new ones, and return the head of the combined list. Either list may be empty. If both are empty, return null.

Examples

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

list1
124null
list2
134null

Every node from both lists appears exactly once, and the values read 1, 1, 2, 3, 4, 4 from smallest to largest.

list1 = [], list2 = [] returns []

Both lists are empty, so the combined list is empty too (return null).

list1 = [], list2 = [0] returns [0]

With list1 empty, the answer is simply list2 as it is.

Constraints

  • 0 <= number of nodes in each list <= 50
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.

Hints

Hint 1

At any moment, the next node of the answer has to be one of the two nodes at the front of the lists.

Hint 2
A pointer toward the approach
Hint 3
The full approach, step by step

Drill This: Your Approach First

Approach

Use a dummy head and a tail pointer. While both lists have nodes, compare their fronts, link the smaller one after tail and advance that list. When one list runs out, attach the rest of the other in one step, since it is already sorted. Each node is linked exactly once and no new nodes are created. O(m + n) time, O(1) extra space, where m and n are the list lengths.

Time

O(m + n)

Space

O(1)

Pitfall

Forgetting to attach the leftover list after the loop drops the tail of the longer list. Without a dummy head you also need special cases for picking the first node and for an empty list.

Solutions

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                tail.next = list1;
                list1 = list1.next;
            } else {
                tail.next = list2;
                list2 = list2.next;
            }
            tail = tail.next;
        }
        tail.next = (list1 != null) ? list1 : list2;
        return dummy.next;
    }
}
Drill This