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^9See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI