24/670

24. Swap Nodes in Pairs

Medium

Walk a linked list two nodes at a time and swap every adjacent pair: the 1st and 2nd nodes trade places, then the 3rd and 4th, and so on. If the list has odd length, the final node has no partner and stays where it is.

Your function receives the node values as an integer array, in list order, and returns the array of values after all the pairwise swaps. Think of it as rewiring next pointers, not editing a value in place — the classic version of this problem forbids touching the values at all, and the pointer surgery is what makes it interesting.

An empty list is valid input and comes back empty.

Adjacent pairs trade places; an odd tail stays put
before12345no partnerafter21435

Example 1:

Input: head = [1, 2, 3, 4]

Output: [2, 1, 4, 3]

Explanation: Nodes 1 and 2 trade places, then nodes 3 and 4 do the same.

Example 2:

Input: head = [1]

Output: [1]

Explanation: A single node has no partner, so nothing moves.

Constraints:

  • 0 ≤ list length ≤ 100
  • -100 ≤ node value ≤ 100

Hints:

The list splits naturally into chunks of two. What should happen inside one chunk, and what should happen to everything after it?

Recursively: swap the first two nodes, and the answer for the rest of the list is the same problem one size smaller — attach it after the swapped pair.

Iteratively: step through positions 0, 2, 4, … and swap each complete pair in place; a leftover single node needs no work. That's one pass with O(1) extra space.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: head = [1, 2, 3, 4]

Expected output: [2, 1, 4, 3]