Swap Nodes in Pairs

35 min · swapPairs()

A line of dancers changes places two at a time: first trades with second, third trades with fourth, and anyone left at the end keeps their spot.

A linked list is a chain of nodes where each node's next field links to the one after it. Given its head, swap every pair of adjacent nodes and return the head of the changed chain. Two nodes are adjacent when one immediately follows the other.

A few ground rules:

  • Swap the nodes by changing links, not by rewriting the values stored inside them.
  • Pair the first node with the second, the third with the fourth, and so on.
  • If the list has odd length, its final unpaired node stays in place.
  • An empty list stays empty.

Constraints

  • 0 <= length <= 10_000
  • -1_000_000_000 <= Node.val <= 1_000_000_000

Hints

Name one pair

Stand just before two nodes and call them first and second. After the swap, second should lead to first, and first should lead to whatever followed the pair.

Protect the head

The first swap changes the head, which makes it awkwardly different from every later swap. Put a temporary node before the head so every pair has a predecessor.

Move from the old first

Once a pair is relinked, the old first node is now the pair's tail. Make it your predecessor for the next round.

Follow-up

Can you finish in one pass with O(1) extra space, changing only next pointers and without building another list?

Visible cases

Examples

Example 1

ready
Input
head = [
  1,
  2,
  3,
  4
]
Expected
[
  2,
  1,
  4,
  3
]
Why
both adjacent pairs trade places

Example 2

ready
Input
head = [
  1,
  2,
  3
]
Expected
[
  2,
  1,
  3
]
Why
the last node has no partner, so it stays put

Example 3

ready
Input
head = []
Expected
[]
Why
an empty chain has no pair to swap

Interview signal

Asked at

AmazonMicrosoftBloomberg
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite