A singly linked list starts at head. You also get two positions, left and right, counted from 1 at the head. Reverse only the nodes from position left through position right; the nodes before and after that stretch keep their order.
Return the head of the changed list. It may be a different node from the original head when left is 1.
Example 1
Input: head = [3, 8, 1, 6, 2, 7], left = 2, right = 5 Output: [3, 2, 6, 1, 8, 7] Why: 8, 1, 6, 2 flips to 2, 6, 1, 8; 3 and 7 stay put
2 more examples and the constraints
Example 2
Input: head = [9], left = 1, right = 1 Output: [9] Why: a stretch of one node is already reversed
Example 3
Input: head = [4, -2, 5], left = 2, right = 2 Output: [4, -2, 5] Why: left equals right, so nothing moves
Constraints
- 1 ≤ number of nodes ≤ 500
- −500 ≤ each node's value ≤ 500
- 1 ≤ left ≤ right ≤ number of nodes
- Follow-up: can you do it in a single pass?
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Copy values, flip, write backO(n)
- One pass, move to frontO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 500 nodes | Verdict |
|---|---|---|---|
| Copy values, flip, write back | O(n) | Works, but extra memory and two passes | |
| One pass, move to front | O(n) | Best; one pass, O(1) space |
n = number of nodes. Both are linear; the second walks only as far as right and stores nothing.
Edge cases to test
- left is 1. The head changes. The
dummynode givespreva place to stand. - left equals right. The loop runs zero times and the list comes back unchanged.
- The whole list. left = 1 and right = n reverses everything;
currends up pointing at null. - Segment at the tail. After the last move,
curr.nextis null, which is correct. - One node. left = right = 1: nothing to do.
Common mistakes
- Returning the old
headwhenleftis 1, which drops the new first node. - Running the move loop
right − left + 1times, which pulls one node from outside the segment. - Writing
prev.next = nxtbeforenxt.next = prev.next, which makesnxtpoint at itself.
How to talk through it
- 1Clarify. Are positions 1-based? Can left equal right? May I change node values, or only links?
- 2Give the easy version. Copy values out, reverse the slice, write them back: O(n) time and O(n) space.
- 3Find the anchor. Everything hinges on the node before the segment. A dummy node makes sure it always exists.
- 4Code the moves. Say the four pointer lines as you write them, and why their order matters.
- 5Test out loud. Run left = 1, left = right, and a segment that ends at the tail.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?