61. Rotate List
mediumRotate a singly linked list to the right by k positions. The trick is realizing you don't move k nodes — you find the new tail with a single split, then close and reopen the loop. Modular-arithmetic trap when k exceeds the list length.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the head of a linked list, rotate the list to the right by k places.
Constraints
The number of nodes in the list is in the range [0, 500].-100 <= Node.val <= 1000 <= k <= 2 * 10^9
Examples
Example 1
head = [1,2,3,4,5], k = 2[4,5,1,2,3]Example 2
head = [0,1,2], k = 4[2,0,1]Explanation: k = 4 is equivalent to k = 1 because the list has length 3.
Example 3
head = [], k = 0[]Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
If k is larger than the list length, most of those rotations cancel out. Take k modulo length first.
Hint 2
Find the original tail, connect tail.next = head to form a temporary cycle.
Hint 3
Walk length − (k % length) − 1 steps from head to land on the new tail. Set newHead = newTail.next, break the cycle by newTail.next = null.
Solution approach
Reveal approach
Close-the-loop, then split. Edge-case: if head is null or k == 0, return head. Walk once to find the tail and the length n. Compute k = k % n; if k == 0, return head (no rotation needed). Close the list into a cycle: tail.next = head. Walk n − k − 1 steps from head to find the new tail. Set newHead = newTail.next, then newTail.next = null. Return newHead. Why this works: rotating right by k is the same as cutting the list at position n − k from the start and stitching the back half to the front. The temporary cycle saves you from juggling two list halves. O(n) time, O(1) extra space.
Complexity
- Time
- O(n)
- Space
- O(1)
Related patterns
- linked-list
- pointer-rewiring
- two-pointers
Related problems
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Microsoft
- Bloomberg
Practice these live with InterviewChamp.AI
Drill Rotate List and Linked Lists problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →