SDE & MLE Prep

21. Merge Two Sorted Lists

Problem

Merge two sorted linked lists into one sorted list by splicing their nodes together, and return its head.

Example: 1→2→4 and 1→3→4 → 1→1→2→3→4→4

Dummy head + tail pointer; repeatedly attach the smaller head. Append the leftover list.

Complexity: O(m + n) time, O(1) space.

class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        dummy = tail = ListNode()
        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
        tail.next = list1 or list2
        return dummy.next