Show problems as
Classic problem #1721MediumLinked ListTwo Pointers

Swapping Nodes in a Linked List

Real-world version: Swapping Two Cars in a Chain
Tracked in this browser only
Read Swapping Nodes in a Linked List on LeetCode(opens in a new tab)

The 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.

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