Reverse Linked List II

MediumLinked Listin-place reversal

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given the head of a singly linked list and two integers left and right with 1 <= left <= right <= n, where positions are numbered from 1. Reverse only the nodes from position left through position right, inclusive, and leave everything outside that range in place. Return the head of the modified list. When left == right, the list is unchanged. Try to do it in one pass with O(1) extra space.

Examples

Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]
The segment 2,3,4 is reversed to 4,3,2.
Input: head = [5], left = 1, right = 1
Output: [5]
A one-node range leaves the list unchanged.

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More in-place reversal problems