Skip to content
Problem 92 · LeetCode 92(opens in a new tab)

Reverse Linked List II

MediumLinked lists

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.

Try it on LeetCode(opens in a new tab)
  1. Copy values, flip, write backO(n)
  2. One pass, move to frontO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 500 nodesVerdict
Copy values, flip, write backO(n)
Works, but extra memory and two passes
One pass, move to frontO(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 dummy node gives prev a 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; curr ends up pointing at null.
  • Segment at the tail. After the last move, curr.next is null, which is correct.
  • One node. left = right = 1: nothing to do.

Common mistakes

  • Returning the old head when left is 1, which drops the new first node.
  • Running the move loop right − left + 1 times, which pulls one node from outside the segment.
  • Writing prev.next = nxt before nxt.next = prev.next, which makes nxt point at itself.

How to talk through it

  1. 1Clarify. Are positions 1-based? Can left equal right? May I change node values, or only links?
  2. 2Give the easy version. Copy values out, reverse the slice, write them back: O(n) time and O(n) space.
  3. 3Find the anchor. Everything hinges on the node before the segment. A dummy node makes sure it always exists.
  4. 4Code the moves. Say the four pointer lines as you write them, and why their order matters.
  5. 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?