Show problems as
Classic problem #24MediumLinked ListRecursion

Swap Nodes in Pairs

Real-world version: Swap Neighbouring Clips
Tracked in this browser only
Read Swap Nodes in Pairs on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstRecursion Technique · Linked List, animated step by step

An editing bench holds a reel: a run of film clips spliced end to end, each clip carrying its own frame count. Splices cannot be handed across, so the reel reaches you as a plain JSON array of frame counts in projection order, the clip nearest the head of the reel first. Hand your answer back in the same form. An array with nothing in it is a reel carrying no clips at all.

Work along the reel two clips at a time and swap each couple over: the first clip and the second clip trade places, then the third and the fourth trade places, and so on to the end. When the reel carries an odd number of clips, the last one has no partner and must be left sitting where it is.

Re-cut the splices, not the film: every clip keeps the frame count it arrived with, and only its position along the run may change. Make a single pass over the reel, in O(n) steps, holding only a constant amount of bookkeeping beyond the reel you return.

Examples

Example 1

Input
reel = [4, 9, 2, 7]
Output
[9, 4, 7, 2]

The first couple trades to put 9 ahead of 4, and the second couple trades to put 7 ahead of 2.

Example 2

Input
reel = [5, 8, 3]
Output
[8, 5, 3]

The leading couple trades over, and the clip holding 3 has nobody to pair with, so it keeps the tail position.

Example 3

Input
reel = [12]
Output
[12]

A lone clip has no partner anywhere on the reel, so the reel is returned exactly as it came in.

Constraints

  • 0 <= reel.length <= 100
  • 0 <= reel[i] <= 100

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def swap_clips(reel: list[int]) -> list[int]:
Java
public int[] swapClips(int[] reel)