Swap Nodes in Pairs
Master this topic with zero to advance depth.
Swap Nodes in Pairs
Swap every two adjacent nodes.
Visual Representation
1 -> 2 -> 3 -> 4
Result: 2 -> 1 -> 4 -> 3Examples
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Approach 1
Level I: Recursive
Intuition
Swap first two nodes, recurse for the rest.
⏱ O(N)💾 O(N)
Approach 2
Level III: Optimal (Iterative)
Intuition
Use a dummy node to simplify head swapping. Use a prev pointer to track the node before the current pair being swapped.
⏱ O(N)💾 O(1)
Detailed Dry Run
Dummy -> 1 -> 2 -> 3 -> 4. Prev = Dummy.
- First = 1, Second = 2.
- Prev.next = 2.
- 1.next = 3.
- 2.next = 1. Prev = 1.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.