Ctrl K

Swap With the Mirror Position

Medium
You are given a singly linked list head and an integer pos. Find the pos-th node from the start and the pos-th node from the end (both counted from 1), and swap their values. Return the head of the list.
Example 1
head=list_node([3, 6, 9, 12, 15, 18]), pos=2 → [3, 15, 9, 12, 6, 18]

The second node from the front holds 6 and the second from the back holds 15, so their values are exchanged.

Example 2
head=list_node([5, 1, 7]), pos=2 → [5, 1, 7]

The second node from the front and from the back is the same node, so the list does not change.

Example 3
head=list_node([40, 50]), pos=1 → [50, 40]

The first from the front is 40 and the first from the back is 50, so they swap.

Constraints
  • The list has n nodes
  • 1 ≤ pos ≤ n ≤ 10⁵
  • 0 ≤ Node.val ≤ 100
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsDrop the K-th Node From the Tail MediumMove the Tail to the Front MediumSorted List, Unique Values Only MediumSplit a List Around a Pivot MediumList Folded From Both Ends Medium
loading Python…
Input
head=list_node([3, 6, 9, 12, 15, 18]), pos=2
Expected
[3, 15, 9, 12, 6, 18]

Run checks the first 3 tests in your browser. Submit checks all 93 tests on the server, hidden ones included.