Ctrl K

Reverse a Slice of a List

Medium
You get a singly linked list head and two positions start ≤ end (nodes are numbered from 1). Reverse the part of the list from node start to node end inclusive and leave every other node where it is. Return the head of the resulting list. Try to do it in a single pass.
Example 1
head=list_node([7, 3, 8, 1, 6, 2]), start=2, end=5 → [7, 6, 1, 8, 3, 2]

Nodes 2 through 5 are 3, 8, 1, 6; reversing them gives 7, 6, 1, 8, 3, 2.

Example 2
head=list_node([-4, 9]), start=1, end=2 → [9, -4]

The whole list gets reversed.

Example 3
head=list_node([11, 12, 13]), start=3, end=3 → [11, 12, 13]

A segment of one node leaves the list unchanged.

Constraints
  • The list has 1 to 500 nodes
  • -500 ≤ Node.val ≤ 500
  • 1 ≤ start ≤ end ≤ list length
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsAdding Digit Lists MediumDrop the K-th Node From the Tail MediumTrade Places in Twos MediumMove the Tail to the Front MediumSorted List, Unique Values Only Medium
loading Python…
Input
head=list_node([7, 3, 8, 1, 6, 2]), start=2, end=5
Expected
[7, 6, 1, 8, 3, 2]

Run checks the first 3 tests in your browser. Submit checks all 99 tests on the server, hidden ones included.