Swap Nodes in Pairs – Solution & Complexity

Solution Walkthrough

  1. Step 1: Recognize the Pattern

    The key pattern is: a dummy-node walk that repoints three links at a time — prev, the first node of the pair, and the second node of the pair. Identify the state and invariant before coding.

  2. Step 2: Build the Algorithm

    Advance one state transition at a time. Mark or update state before exploring dependent work.

  3. Step 3: Check Edge Cases

    Test empty or minimal input, skewed shapes, duplicates where allowed, and impossible outcomes.

  4. Step 4: Solution and Complexity

    Time: O(n) — every node is visited once. Space: O(1) auxiliary for the iterative Python/JavaScript/Java/Go solutions. The Rust solution here is written recursively for idiomatic ownership handling of Option<Box<ListNode>> swaps, so it costs O(n) call-stack space instead.

    All 5 languages below run and submit against the remote judge for this problem — Java/Go/Rust use the same real ListNode structural-type support the judge added for the rest of the linked-list/tree track.

    def swap_pairs(head: ListNode) -> ListNode:
        dummy = ListNode(0, head)
        prev = dummy
    
        while prev.next and prev.next.next:
            first = prev.next
            second = first.next
            first.next = second.next
            second.next = first
            prev.next = second
            prev = first
    
        return dummy.next

FAQ