Skip to main content

92. Reverse Linked List II

medium

Reverse a sub-segment of a singly linked list from position left to position right, in a single pass, in place. The bounded-reversal cousin of Reverse Linked List that interviewers reach for when they want to see if you can keep four pointers straight at once.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list. Follow up: Could you do it in one pass?

Constraints

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

Examples

Example 1

Input
head = [1,2,3,4,5], left = 2, right = 4
Output
[1,4,3,2,5]

Example 2

Input
head = [5], left = 1, right = 1
Output
[5]

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

Use a dummy head so left = 1 isn't a special case. Walk left − 1 steps from dummy to land on the node just before the segment.

Hint 2

Once you're at that 'pre' node, reverse the next right − left + 1 nodes using the standard three-pointer reversal, but stop after that count.

Hint 3

After reversing, you need to stitch: pre.next was the old segment head (now its tail) — point that tail at whatever node followed the segment. The new segment head is the last-reversed node.

Solution approach

Reveal approach

Dummy-head plus bounded three-pointer reversal — head-insertion variant. Allocate dummy with dummy.next = head and set pre = dummy. Walk left − 1 steps so pre lands just before position left. Let curr = pre.next (the first node that will be reversed). Repeat right − left times: stash next = curr.next; rewire curr.next = next.next; next.next = pre.next; pre.next = next. Each iteration pulls the node immediately after curr to the front of the segment, growing the reversed prefix in place while curr stays put and becomes the segment's tail. Return dummy.next. One pass, O(n) time, O(1) extra space.

Complexity

Time
O(n)
Space
O(1)

Related patterns

  • linked-list
  • dummy-head
  • in-place-linked-list-reversal
  • pointer-rewiring

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Amazon
  • Microsoft
  • Meta
  • Bloomberg

Practice these live with InterviewChamp.AI

Drill Reverse Linked List II and Linked Lists problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →