Skip to content
Decoder

Reverse Linked List II

Medium

Problem

You get the head of a linked list and two positions left and right, counted from 1. Reverse only the nodes from position `left` to position `right`, keep everything outside that stretch where it was, and return the head. Try to do it in one pass by relinking nodes.

Example 1

Input
1
Output
2 -> 3 -> 4 -> 5, left = 2, right = 4 → 1 -> 4 -> 3 -> 2 -> 5

Example 2

Input
5, left = 1, right = 1
Output
5

Example 3

Input
1
Output
2 -> 3, left = 1, right = 3 → 3 -> 2 -> 1

Constraints

  • 1 <= number of nodes <= 500
  • -500 <= Node.val <= 500
  • 1 <= left <= right <= number of nodes

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.