Skip to content

visual walkthrough

Swap Nodes in Pairs

MediumIn-place ReversalReported at: MetaAmazonMicrosoft+3

Local pointer rewiring in pairs.

Solve on LeetCode

The idea

Swapping two nodes means changing three arrows: the one into the pair, the one between them, and the one out of the pair.

Change them in the right order (first point a past b) and nothing is ever lost. A dummy head gives the first pair a "prev" too.

Complexity

approachtimespace
Array of nodesO(n)O(n)
Relink each pairO(n)O(1)

More walkthroughs