InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Linked List

Reverse Linked List II

medium Original ↗ 00:00

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.

With small n, the difficulty is the pointer manipulation, not performance, especially the case left = 1.

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 For a single pass, 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug