Swap Nodes in Pairs
Swap Nodes in Pairs is a medium linked list problem solved with the dummy node pattern pattern.
The best approach, optimal (iterative with a dummy node), runs in O(n) time and O(1) space.
Below are 2 approaches in Java, from recursive up.
Problem
Swap every two adjacent nodes of a linked list and return the new head. Change the links, not the values stored in the nodes.
Examples
Example 1
- Input
head = [1, 2, 3, 4, 5]- Output
[2, 1, 4, 3, 5]- Why
- The odd node at the end stays put.
Example 2
- Input
head = []- Output
[]
Constraints
- The list has
0to100nodes. - Swap nodes, not values.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.
| Approach | Time | Space |
|---|---|---|
| Recursive | O(n) | O(n) |
| Optimal (iterative with a dummy node) | O(n) | O(1) |
1Recursive
O(n)O(n)Recursion depth n / 2.Swap the first two nodes and recursively swap the rest starting from the third.
- If fewer than 2 nodes, return head.
- second = head.next; head.next = swapPairs(second.next); second.next = head; return second.
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;
ListNode second = head.next;
head.next = swapPairs(second.next);
second.next = head;
return second;
}
}2Optimal (iterative with a dummy node)
O(n)O(1)prev sits before the pair (a, b). Relink prev → b → a → rest, then move prev to a.
- prev = dummy.
- While prev.next and prev.next.next exist: a = prev.next, b = a.next.
- a.next = b.next; b.next = a; prev.next = b; prev = a.
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0, head), prev = dummy;
while (prev.next != null && prev.next.next != null) {
ListNode a = prev.next, b = a.next;
a.next = b.next;
b.next = a;
prev.next = b;
prev = a;
}
return dummy.next;
}
}Edge cases to test
- Empty list or single node
- Odd length
Hints
Hint 1
With a dummy before the pair, you need three pointer changes per swap.
FAQ
What is the best time complexity for Swap Nodes in Pairs?
Optimal (iterative with a dummy node) runs in O(n) time and O(1) extra space.
Which pattern does Swap Nodes in Pairs use?
It is a linked list problem that uses the dummy node pattern pattern. Other problems with the same pattern: Remove Linked List Elements, Delete Nodes From Linked List Present in Array, Merge Two Sorted Lists.
Is there a brute force solution for Swap Nodes in Pairs?
Yes. Recursive takes O(n) time and O(n) space. Swap the first two nodes and recursively swap the rest starting from the third.
Which edge cases should I test for Swap Nodes in Pairs?
Empty list or single node; Odd length.