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

Problem

You get the head of a linked list and a number k. Rotate the list to the right by k places: each place moves the last node to the front.

Return the head of the rotated list. k can be larger than the length of the list.

Constraints

  • 0 ≤ number of nodes ≤ 30
  • -100 ≤ Node.val ≤ 100
  • 0 ≤ k ≤ 100

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: One pass finds the tail and the length, and a second walk takes at most n hops.

Space: Only a few pointers and counters are used. The nodes are re-linked in place.

Walk to the tail while counting the nodes, then link the tail back to the head to make a ring. Rotating right by k is the same as rotating by k mod n, so the new tail is n minus k mod n hops forward from the old tail. Stop there, take its next node as the new head, and cut the ring open.