InterviewHubPRO
Section Overview
Q38

Question 38 of 100

Part 5: Linked Lists & Fast-Slow Pointers (37 - 45)

38%
DSA Patterns (Multi-Lang)•Part 5: Linked Lists & Fast-Slow Pointers (37 - 45)

Merge Two Sorted Lists.

In Simple Words: Use a dummy head node. Compare l1.val and l2.val, splice the smaller node into tail.next, and advance that list. Append remaining non-empty list.

  • Time: $O(N + M)$ | Space: $O(1)$
Multi-Language Solutions
Switch tabs or choose All
def mergeTwoLists(l1: ListNode | None, l2: ListNode | None) -> ListNode | None:
    dummy = ListNode(0)
    tail = dummy
    while l1 and l2:
        if l1.val <= l2.val:
            tail.next = l1
            l1 = l1.next
        else:
            tail.next = l2
            l2 = l2.next
        tail = tail.next
    tail.next = l1 if l1 else l2
    return dummy.next