330. Reverse a Section

A museum guides visitors through a corridor of exhibits stored as a chain: each node holds an exhibit number and a link to the next exhibit, and head is the first one. For one special tour the curator wants the stretch of exhibits from position left to position right (both counted from 1, both included) to be visited in reverse order, while everything before and after that stretch stays in place.

Return the head of the chain after reversing exactly that stretch. If left == right, nothing changes. Try to do it in one pass over the chain, relinking the existing nodes rather than building a new chain. You may assume 1 <= left <= right <= the chain length.

Example 1

Input:
head = [10,20,30,40,50,60], left = 2, right = 5
Output:
[10,50,40,30,20,60]
Explanation:

Positions 2 to 5 hold 20, 30, 40, 50. Reversed they read 50, 40, 30, 20: 10, 50, 40, 30, 20, 60.

Example 2

Input:
head = [7,3,8], left = 1, right = 3
Output:
[8,3,7]
Explanation:

The stretch covers the whole chain, so the result is 8, 3, 7.

Constraints

1 ≤ chain length ≤ 105
-1000 ≤ node value ≤ 1000
1 ≤ left ≤ right ≤ chain length

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)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…