InterviewPrepKit

Home / Coding / Linked List

Reverse Linked List II

medium Original β†—
Solving tips
  • Use a dummy node so left = 1 (returned head changes) is not a special case; park a pointer at position left-1.
  • Cut-reverse-reconnect: reverse right-left+1 nodes, then repair two seams (predecessor to new head, old window head to the successor).
  • The elegant single-pass alternative is head insertion: right-left times, pluck the node after the window start and move it to the front of the window.
  • Mind the loop counts: cut-and-reverse runs right-left+1 times (nodes), head insertion runs right-left times (moves). Target O(n) time, O(1) space.

Problem

Given the head of a singly linked list and two 1-indexed positions left and right (with left <= right), reverse the nodes from position left through position right β€” and only those β€” then return the head. Nodes before left and after right keep their places and stay connected to the reversed segment.

The follow-up asks for a single pass over the list.

Examples

  • Input: head = [1, 2, 3, 4, 5], left = 2, right = 4 β†’ Output: [1, 4, 3, 2, 5] The segment 2β†’3β†’4 reverses to 4β†’3β†’2; 1 and 5 are untouched.
  • Input: head = [5], left = 1, right = 1 β†’ Output: [5] A one-node segment reversed is itself.
  • Input: head = [3, 7], left = 1, right = 2 β†’ Output: [7, 3] The segment includes the head, so the returned head changes.

Constraints

  • 1 <= n <= 500 where n is the number of nodes.
  • -500 <= Node.val <= 500.
  • 1 <= left <= right <= n.

Small n means performance is not the challenge β€” surviving the pointer surgery (especially when left = 1) is.

Think about it first

Hint 1 You already know how to reverse a whole list with the prev/curr iteration. What extra bookkeeping does reversing only a window require?
Hint 2 Two boundary connections must survive: (node at leftβˆ’1) β†’ (node at right), and (node at left) β†’ (node at right+1). Notice the node that *was* at position left ends up as the tail of the reversed window.
Hint 3 One elegant single-pass trick: anchor a pointer at position leftβˆ’1 (use a dummy for left = 1). Then, right βˆ’ left times, take the node just after the window's start and move it to the front of the window ("head insertion"). Each move shifts one node into reversed position.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.