CodingNodes / Linked List / Reverse Linked List II System design Space play · ←→ step · R restart

Problem

You get the head of a linked list and two positions left and right, counted from 1 at the head.

Reverse the nodes from position left to position right, and leave every other node where it is. Return the head of the list.

Constraints

  • 1 ≤ number of nodes ≤ 30
  • -100 ≤ Node.val ≤ 100
  • 1 ≤ left ≤ right ≤ number of nodes

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: prev walks at most left steps and the section is handled with right minus left constant-time moves.

Space: Only a dummy node and three pointers are used. The nodes are re-linked in place.

Put a dummy before the head and walk prev to the node just before position left. Let cur be the first node of the section. Then repeat right minus left times: take the node after cur, unhook it, and link it in right after prev. cur never moves, so each pass slides the next node to the front of the section and the section ends up reversed.