315. Swap Mirror Nodes
A museum arranges its exhibits along a corridor stored as a chain of nodes; each node holds the inventory number of an exhibit. The curator wants to swap two exhibits that are mirror images of each other: the k-th exhibit counted from the entrance (the head) and the k-th exhibit counted from the far end (the tail). Both counts start at 1.
Given the head of the chain and an integer k, swap the values of these two nodes and return the head. If k is the middle of an odd-length chain, both counts point to the same node and nothing changes. The chain length is not given, and it may reach 100,000 nodes, so find the second node with a single sweep instead of measuring the chain first.
Example 1
- Input:
- head = [10,20,30,40,50], k = 2
- Output:
- [10,40,30,20,50]
- Explanation:
The 2nd node from the front holds 20 and the 2nd from the back holds 40. After swapping their values the chain is [10, 40, 30, 20, 50].
Example 2
- Input:
- head = [9,3,6,2], k = 4
- Output:
- [2,3,6,9]
- Explanation:
The 4th node from the front is 2 and the 4th from the back is 9 (the head). Result: [2, 3, 6, 9].
Constraints
1 ≤ k ≤ chain length ≤ 105
-1000 ≤ node value ≤ 1000
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms
Expected complexity
- Time
- O(n)
- Space
- O(1)