Swapping Nodes in a Linked List
Real-world version: Swapping Two Cars in a ChainThe statement here is our own: the same inputs, outputs and technique.
A conveyor is built from cars clipped one behind another. Each car carries a load and a clip to the car behind it, and the car at the end has an empty clip. Nothing on the conveyor records how many cars it holds.
Because the harness passes plain JSON, the conveyor reaches you as chain, listing the loads in clip order from the front car.
Swap the loads of the k-th car counted from the front and the k-th car counted from the end, both counted from one. Return the conveyor afterwards.
Examples
Example 1
- Input
- chain = [9, 8, 7], k = 1
- Output
- [7, 8, 9]
The first car from the front and the first from the end are the two ends of the conveyor, so their loads change places.
Example 2
- Input
- chain = [4, 5], k = 2
- Output
- [5, 4]
With two cars, the second from the front is the last car and the second from the end is the first, so again the two ends swap.
Example 3
- Input
- chain = [1, 2, 3], k = 2
- Output
- [1, 2, 3]
With three cars, the second from the front and the second from the end are the same middle car, so nothing changes.
Constraints
- 1 <= k <= chain.length <= 10^5
- 0 <= chain[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_nodes(chain: list[int], k: int) -> list[int]:public int[] swapNodes(int[] chain, int k)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 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