LeetCode #24 Medium

Swap Nodes in Pairs

Swap Nodes in Pairs is LeetCode 24 (Medium). Given the head of a singly linked list, swap every two adjacent nodes and return the head of the changed list.

  • Change the links between nodes; changing the values stored in them is not allowed.
  • When the length is odd, the last node keeps its place.

The list has at most 100 nodes, so the challenge is getting the pointer changes right, not speed.

Constraints
  • The number of nodes in the list is in the range [0, 100].
  • 0 <= Node.val <= 100
linked-listrecursion
Open on LeetCode ↗
02

Intuition

To swap adjacent nodes in a linked list, look at one pair a → b. Swapping it changes three links, not two: the link into the pair, the link between a and b, and the link out of the pair. The link into the pair belongs to the node before a, so keep a pointer prev to that node.

The first pair has no node before it. A dummy node in front of the head gives it one, so every pair is handled the same way, and the new head is simply dummy.next.

After the swap, a is the second node of its pair, which makes it prev for the next pair.

How to spot this pattern

Any linked-list task that rewires nodes near the head, such as removing, reversing or swapping, gets simpler with a dummy node, because the head stops being a special case.

03

Approach

Try it first

Before reading on, draw prev → 1 → 2 → 3 and list which next pointers must change to get prev → 2 → 1 → 3. In what order can you change them without losing node 3? Aim for O(1) extra space.

1

Put a dummy node in front

Create dummy with dummy.next = head and set prev = dummy. Now the first pair has a node before it like every later pair, and the answer is dummy.next at the end.

2

Check that a full pair is left

Loop while prev.next and prev.next.next both exist. If only one node or none remains, there is nothing to swap, which is how an odd last node stays in place.

3

Change the three links

Call the pair a = prev.next and b = a.next. Set prev.next = b, then a.next = b.next, then b.next = a. The second change saves the rest of the list in a.next before the third one overwrites b.next, its only other pointer.

4

Step past the pair

Set prev = a. After the swap a is second in its pair, so it is the node right before the next pair.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def swapPairs(self, head):
▶3 dummy = ListNode(0, head)
▶4 prev = dummy
▶5 while prev.next and prev.next.next:
▶6 a, b = prev.next, prev.next.next
▶7 prev.next = b
▶8 a.next = b.next
▶9 b.next = a
▶10 prev = a
▶11 return dummy.next
Dprev1234dummynulldummy node placed before the head
list[1, 2, 3, 4]
prevdummy
A dummy node D is placed before the head, and prev starts there. Now the first pair also has a node in front of it, so it is swapped exactly like every later pair.
Dprev1a2b34dummynulltwo nodes after prev → swap 1 and 2
a1
b2
after b3
Both prev.next and prev.next.next exist, so a full pair is waiting: a = 1 and b = 2. Three links have to change: the one into the pair (from dummy), the one between a and b, and the one out of the pair (to node 3).
Dprev1a2b34dummynulldummy now points to 2
prev.next2
Point dummy at 2, the node that will come first. Node 1 is no longer reached from the front, but a still holds it, so nothing is lost.
Dprev1a2b34dummynullnode 1 now points to 3
a.next3
Node 1 will be second, so it takes over the link out of the pair: it now points to 3. This has to happen before the next change, because b.next is the only other pointer to the rest of the list.
Dprev1a2b34dummynullnode 2 now points back to 1
b.next1
Finally point 2 at 1. Follow the links from dummy: 2, then 1, then 3. The pair is swapped.
D21prev34dummynullprev moves to 1, the end of the pair
list[2, 1, 3, 4]
prev1
Redrawn in list order, every link is straight again. Node 1 is now the second node of its pair, so it is the node right before the next pair, and prev moves to it.
D21prev3a4bdummynulltwo nodes after prev → swap 3 and 4
a3
b4
after bnull
Both prev.next and prev.next.next exist, so a full pair is waiting: a = 3 and b = 4. Three links have to change: the one into the pair (from node 1), the one between a and b, and the one out of the pair (to null).
D21prev3a4bdummynullnode 1 now points to 4
prev.next4
Point node 1 at 4, the node that will come first. Node 3 is no longer reached from the front, but a still holds it, so nothing is lost.
D21prev3a4bdummynullnode 3 now ends the list
a.nextnull
Node 3 will be second, so it takes over the link out of the pair: it now points to null. This has to happen before the next change, because b.next is the only other pointer to the rest of the list.
D21prev3a4bdummynullnode 4 now points back to 3
b.next3
Finally point 4 at 3. Follow the links from node 1: 4, then 3, then null. The pair is swapped.
D2143prevdummynullprev moves to 3, the end of the pair
list[2, 1, 4, 3]
prev3
Redrawn in list order, every link is straight again. Node 3 is now the second node of its pair, so it is the node right before the next pair, and prev moves to it.
D2143dummynullno node left → list is 2, 1, 4, 3
after prevno node
result[2, 1, 4, 3]
Nothing follows prev, so the loop stops. The answer is dummy.next, which is node 2, not the old head 1.
05

Recursive swap

If fewer than two nodes remain, return the list as it is. Otherwise second becomes the new front, the old head points to the swapped rest of the list, and second points to the old head.

▶1class Solution:
▶2 def swapPairs(self, head):
▶3 if not head or not head.next:
▶4 return head
▶5 second = head.next
▶6 head.next = self.swapPairs(second.next)
▶7 second.next = head
▶8 return second
06

Common pitfalls

Returning the old head

✗ Wrong
return head
✓ Right
return dummy.next

head still points at the old first node, which is now second. For [1, 2, 3, 4] returning it gives [1, 4, 3], and node 2 is lost.

Moving prev to the wrong node

✗ Wrong
prev = b
✓ Right
prev = a

After the swap the order is b → a, so b is first, not last. For [1, 2, 3, 4] the next round swaps nodes 1 and 3 and the result is [2, 3, 4, 1] instead of [2, 1, 4, 3].

07

Edge cases

Empty list or a single node

The loop condition fails at once and dummy.next is returned, which is head itself (None for an empty list).

08

Complexity

Time
O(n)
Space
O(1)
Each pair is visited once and costs three pointer changes. Only dummy, prev, a and b are extra.
09

Swap Nodes in Pairs FAQ

Why not just swap the values?

The problem forbids it, and for a reason: in real code a node can carry a large payload or be referenced from elsewhere, so moving data is not the same as moving nodes. The exercise is about relinking.

How does this relate to Reverse Nodes in k-Group?

Swapping pairs is the k = 2 case of Reverse Nodes in k-Group. For larger k you first check that k nodes remain, reverse them in a loop and reconnect both ends; with k = 2 the reversal is the three link changes here.