All problems
1061MediumLinked ListTwo Pointers

Swapping Two Cars in a Chain

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1721Swapping Nodes in a Linked List

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def swap_nodes(chain: list[int], k: int) -> list[int]:
Java
public int[] swapNodes(int[] chain, int k)
September 7
Apply