Browse curriculum

FAANGPrep Sprint

Swap Nodes in Pairs

Swap every two adjacent nodes.

Problem Understanding

Walk a linked list two nodes at a time and swap each pair of neighbours, then return the new head. The swap has to rewire the next pointers; copying values between nodes is not allowed.

Example: 1->2->3->4 becomes 2->1->4->3.

Attempt 1: Swapping Values

We could just iterate through the list and swap curr.val with curr.next.val. This is easy and perfectly fine in many real-world scenarios, but interviewers explicitly ban it to test your pointer manipulation skills.

Visualizing the Issue

To swap nodes A and B (prev -> A -> B -> next), we need to change 3 pointers:

  1. prev.next should point to B.
  2. A.next should point to next.
  3. B.next should point to A.

The Intuition: Iterative vs Recursive

Recursive: Swap the first two nodes, then recursively call the function for the rest of the list.
Iterative: Use a dummy node and a prev pointer to handle swaps in a loop.

Interactive Walkthrough

4 NODES · VALUES NEVER MOVE

DUMMY BEFORE HEAD

prev

·

dummy

→

1

#0

→

2

#1

→

3

#2

→

4

#3

→ NULL

Pairs swapped

0

 

dummy.next = head, and prev starts on dummy — the first pair has a node before it like every other pair

Next

prev.next (1) and prev.next.next (2) both exist — swap them

Values

Watch the three pointer assignments that swap each pair, one step each. Values never move — every node keeps its number from the first step to the last — only next pointers change.