FAANGPrep Sprint
Swap Nodes in Pairs (LeetCode 24)
Swap Nodes in Pairs (LeetCode 24): 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:
prev.nextshould point toB.A.nextshould point tonext.B.nextshould point toA.
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.
Swap Nodes in Pairs Visualization
4 NODES · VALUES NEVER MOVE
DUMMY BEFORE HEAD
prev
dummy
→
#0
→
#1
→
#2
→
#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.
