Skip to the code
cf.
+25 XP

#240 Reverse a Stretch of the Queue

medium

A support tool lists waiting tickets in a linked list. An agent selects tickets from position left to position right (counting from 1) and clicks "reverse selection".

Write reverseStretch(head, left, right) that reverses only the nodes from position left to position right, keeps the rest in place, and returns the head. Do it in one pass if you can.

Example 1

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

Positions 2 to 4 hold 2, 3, 4, which become 4, 3, 2.

Example 2

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

Reversing one node changes nothing.

Constraints

  • The list has 1 to 500 nodes.
  • -500 <= node.val <= 500
  • 1 <= left <= right <= the number of nodes

Lists are written as arrays here, like [1, 2, 3]. Your function works with ListNode objects, each with val and next.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).