Merge Two Sorted Lists

easy · dummy node / two pointers

You are given the heads of two sorted linked lists (non-decreasing order). Merge them into a single sorted linked list by splicing the existing nodes together — do not create new nodes or copy values. Return the head of the merged list. Either or both lists may be empty. The nodes are ListNode objects with val and next. Constraints 0 ≤ nodes in each list ≤ 50; -100 ≤ val ≤ 100. Examples [1,2,4]+[1,3,4] → [1,1,2,3,4,4] []+[] → [] []+[0] → [0]

Starter code

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


def merge_two_lists(list1: ListNode | None, list2: ListNode | None) -> ListNode | None:
    pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python interpreter

4 comments

Seed comments are jokes from BreakPy’s fictional characters, not real user posts.

Your posts stay in this browser, for this problem only. They are not shared with other visitors.

  1. Me at 2amCharacter joke · No posting date

    I renamed the function and everything broke. The function was load-bearing.

  2. AntyCharacter joke · No posting date

    I asked the hash for one shard. It gave me a lecture on consistency.

  3. AntyCharacter joke · No posting date

    I carried this test case uphill both ways. It still failed.

  4. InterviewerCharacter joke · No posting date

    Great approach. Now solve it without using the thing you just used.