Rotate List
1 approach, code in every language
Problem description
Given the head of a singly linked list and an integer k, shift the whole list to the right by k positions. Rotating right by one means the current tail moves to the front while everything else slides down by one slot.
Because k can be much larger than the list length, rotating by k is the same as rotating by k modulo the length. Return the head of the list after the rotation.
Example 1
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
The last two nodes (4 and 5) wrap around to the front while the rest keep their order.
Example 2
Input: head = [0,1,2], k = 4
Output: [2,0,1]
With length 3, rotating by 4 is the same as rotating by 4 % 3 = 1, so only the tail 2 moves to the front.
Constraints
The number of nodes is in the range [0, 500].-100 <= Node.val <= 1000 <= k <= 2 * 10^9
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Rundown Cue Shift is our own problem on the technique behind Rotate List: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free