Swap Nodes in Pairs

Medium

Topics
Linked ListRecursion

Given the head of a linked list, swap every two adjacent nodes and return its head. You must swap the nodes themselves, not just their values. A trailing odd node stays in place.

Example 1

before1234null
after2143null
Adjacent pairs swap, marked by the dashed separators. The values must not simply be exchanged — the nodes have to be relinked — so each step rewires three pointers and the final odd node, if any, stays put.
Linked list values from head to tail.
Input:  head = [1,2,3,4]
Output: [2,1,4,3]

Example 2

before123null
after213null
Input:  head = [1,2,3]
Output: [2,1,3]

Constraints

  • 0 <= number of nodes <= 100
  • 0 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

Swapping adjacent nodes means rewiring three links per pair, and the node that has to change is the one before the pair — which for the first pair is the head itself. A dummy node in front makes every pair look identical and removes the special case.

Keep prev at the node preceding the pair. Name the pair a and b, then write the three links: a jumps over b, b points back at a, and prev points at b. Afterwards a is the node preceding the next pair, so it becomes the new prev.

Approach

  1. Create a dummy whose next is the head; set prev to it.
  2. While prev.next and prev.next.next both exist, take a = prev.next and b = a.next.
  3. Rewire: a.next = b.next, then b.next = a, then prev.next = b.
  4. Set prev = a and continue.
  5. Return dummy.next.

Dry Run

input  1 -> 2 -> 3 -> 4

pair (1,2)   a=1 b=2
  a.next = b.next      1 -> 3
  b.next = a           2 -> 1
  prev.next = b        dummy -> 2
  prev = a             prev is now 1

pair (3,4)   a=3 b=4   same three writes

answer  2 -> 1 -> 4 -> 3

  [1,2,3]  ->  2 -> 1 -> 3     the odd tail stays put
  [1]      ->  1
  []       ->  empty

Complexity

  • Time — O(n): each pair is handled once with constant work.
  • Space — O(1): a dummy and three pointers. The recursive formulation is equally short but costs O(n) frames, which the iterative version avoids.

Common Pitfalls

  • Swapping the values instead of the nodes. The problem forbids it explicitly, and it is the first thing an interviewer checks for.
  • Testing only prev.next. Both prev.next and prev.next.next must exist, or the last odd node is dereferenced through a null.
  • Writing the three links in the wrong order. a.next must be read from b before b.next is overwritten, otherwise the rest of the list is lost.
  • Advancing prev to b. After the swap, a is the trailing node of the pair, so it is the one preceding the next pair.
  • Working without a dummy and then special-casing the head. It is doable and it roughly doubles the code.
  • Reversing the whole list in pairs of values and calling it done when the list has odd length. The trailing node must be left alone, which the loop condition handles for free.

Full Solution — all languages

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def swapPairs(self, head):
        dummy = ListNode(0, head)
        prev = dummy
        while prev.next and prev.next.next:
            a = prev.next
            b = a.next
            a.next = b.next
            b.next = a
            prev.next = b
            prev = a
        return dummy.next
SensAI
Beta
Tap the mic to stop voice mode