AAlgoLoopSpaced repetition for LeetCode
MEDIUMLinked ListLeetCode ↗

Rotate List

The key idea

Rotating right by k only moves the last k % len nodes to the front. Close the list into a ring, then re-open it k % len steps before the old tail so the new head and new tail fall in the right place.

Problem

Given the head of a linked list, rotate the list to the right by k places.

Each rotation moves the last node of the list to the front. Doing this k times shifts every node k positions to the right, and the nodes that fall off the end wrap around to the beginning. Because rotating by the list's length n returns the original list, only k % n actually matters.

Constraints

Examples

Input: head = [1,2,3,4,5], k = 2 Output: [4,5,1,2,3]
Input: head = [0,1,2], k = 4 Output: [2,0,1]

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Linked List problems