oneby7

Linked Lists Reversing and rewiring

306. Reverse Linked List II

Medium

You are given head, the first node of a singly linked list, and two integers left and right. Reverse the order of the nodes from position left to position right, and return the head of the list.

Positions start at 1: the head is node 1, the node after it is node 2, and so on. The nodes before position left and the nodes after position right stay where they are.

The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 → 1 → 6. The output shows the node you return the same way, as the list from that node on.

Example 1

head
38-16295
output
326-1895

Input: head = [3, 8, -1, 6, 2, 9, 5], left = 2, right = 5

Output: [3,2,6,-1,8,9,5]

Explanation: Nodes 2 to 5 hold 8, -1, 6 and 2. They come back in the order 2, 6, -1, 8. The node holding 3 stays first, and the nodes holding 9 and 5 stay at the end.

Example 2

40-1025
head
-104025
output

Input: head = [40, -10, 25], left = 1, right = 2

Output: [-10,40,25]

Explanation: The stretch starts at the head, so the head changes. The node holding -10 is the new head, and the node holding 40 comes after it.

Example 3

6-40-4
head
6-4-40
output

Input: head = [6, -4, 0, -4], left = 3, right = 4

Output: [6,-4,-4,0]

Explanation: The stretch ends at the last node. The last two nodes swap places, so the list now ends with the node holding 0.

Check your understanding

Work out the answer for this input before you write any code.

head = [9, 4, 7, 1, 3, 8], left = 2, right = 4

Constraints

  • 1 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • 1 ≤ left ≤ right ≤ number of nodes

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.