39. Swap Nodes in Pairs
mediumAsked at RedditSwap every two adjacent nodes in a linked list. Reddit asks this to test multi-pointer manipulation — the same pattern needed when re-ordering pairs of items in their ranked feed during an A/B test.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Source citations
Public interview reports confirming this problem appears in Reddit loops.
- Glassdoor (2026-Q1)— Reddit phone screen for backend roles.
Problem
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed).
Constraints
The number of nodes in the list is in the range [0, 100].0 <= Node.val <= 100
Examples
Example 1
head = [1,2,3,4][2,1,4,3]Example 2
head = [][]Example 3
head = [1][1]Approaches
1. Recursive
Swap first two, then recurse on the rest.
- Time
- O(n)
- Space
- O(n)
function swapPairs(head) {
if (!head || !head.next) return head;
const next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}Tradeoff: Clean. O(n) recursion stack.
2. Iterative with dummy head (optimal)
Dummy head; pointer prev. Each iteration: pick first and second, re-wire prev->second->first->rest.
- Time
- O(n)
- Space
- O(1)
function swapPairs(head) {
const dummy = { next: head };
let prev = dummy;
while (prev.next && prev.next.next) {
const first = prev.next;
const second = first.next;
first.next = second.next;
second.next = first;
prev.next = second;
prev = first;
}
return dummy.next;
}Tradeoff: O(1) space. The dummy head handles the swap at the front.
Reddit-specific tips
Reddit interviewers grade on careful re-wiring without losing pointers. Bonus signal: draw a quick diagram with arrows in your screen-share. Mention 'reverse nodes in k-group' (LC 25) as the generalization.
Common mistakes
- Forgetting to save second.next before re-wiring.
- Updating prev to second instead of first (must be first since first now follows second).
- Stack-overflow for very long lists in the recursive version.
Follow-up questions
An interviewer at Reddit may pivot to one of these next:
- Reverse nodes in k-group (LC 25).
- Reverse linked list (LC 206).
- Rotate list (LC 61).
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
FAQ
Why does prev become first?
After the swap the order is second -> first -> rest. The next pair starts after 'first', so prev = first.
Is in-place vs. value swap forbidden?
The problem says 'do not modify values'. Re-wire pointers only — this matters for nodes with payloads beyond .val.
Practice these live with InterviewChamp.AI
Drill Swap Nodes in Pairs and other Reddit interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →