Topicsβ€ΊLinked Listβ€ΊSwap Nodes in Pairs
πŸ“–

Swap Nodes in Pairs

Linked List
~20 min read
5 practice problems

Overview

Swap nodes in pairs means swapping every two adjacent nodes in a linked list: (1,2) β†’ (2,1), (3,4) β†’ (4,3), etc. If the length is odd, the last node stays. You do it in-place with a Dummy Head so the first pair is handled like every other pair: keep a prev pointer to the node before the current pair, then rewire the three links (prev β†’ second, first β†’ second.next, second β†’ first), and advance prev to the node that is now second in the pair.

Key idea: For each pair (first, second), you need to set: the node before the pair points to second; first points to what second pointed to; second points to first. A dummy gives you a consistent "node before the pair" for the first pair.


When to Use

  • Swap nodes in pairs β€” Exact problem.
  • Reverse in fixed-size groups β€” Same idea generalizes to Reverse Nodes in K-Group (k=2 is swap pairs).

How It Works

  1. Dummy: dummy.next = head; prev = dummy.
  2. While there are at least two nodes (prev.next and prev.next.next exist):
  • first = prev.next, second = prev.next.next.
  • prev.next = second.
  • first.next = second.next.
  • second.next = first.
  • prev = first (the node that is now second in the pair; the next "pair" starts after it).
  1. Return dummy.next.

Example 1: Swap Nodes in Pairs

Problem: Given the head of a linked list, swap every two adjacent nodes and return the new head. You may not modify values, only pointers.

function swapPairs(head: ListNode | null): ListNode | null {
  const dummy = new ListNode(-1);
  dummy.next = head;
  let prev: ListNode = dummy;
  while (prev.next !== null && prev.next.next !== null) {
    const first = prev.next;
    const second = prev.next.next;
    prev.next = second;
    first.next = second.next;
    second.next = first;
    prev = first;
  }
  return dummy.next;
}
  • Time: O(n), Space: O(1).

Edge Cases

  • Empty list β€” Loop doesn't run; return dummy.next (null).
  • Single node β€” prev.next.next is null; loop doesn't run; return head.
  • Two nodes β€” One iteration; result is second β†’ first β†’ null.

Common Mistakes

  1. Losing references β€” Save first and second (or second.next) before rewiring; first.next must become second.next before you overwrite second.next.
  2. Wrong advance β€” After swapping, the "previous" for the next pair is the node that was first (now in second position); so prev = first.
  3. Skipping the dummy β€” Without it, the first pair has no "prev"; you'd need separate logic for the head.

Time and Space Complexity

  • Time: O(n).
  • Space: O(1).

Summary