Swap Nodes in Pairs
Real-world version: Swap Neighbouring ClipsThe statement here is our own: the same inputs, outputs and technique.
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.
def swap_clips(reel: list[int]) -> list[int]:public int[] swapClips(int[] reel)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's