Rotate List - Problem

You're given the head of a singly linked list, and your task is to rotate the list to the right by k places.

What does rotation mean? Rotating a linked list to the right by k places means taking the last k nodes from the end and moving them to the front of the list.

Example:

  • Original list: 1 → 2 → 3 → 4 → 5
  • Rotate right by 2: 4 → 5 → 1 → 2 → 3

The challenge is to handle this efficiently without creating a new list, and to deal with edge cases like when k is larger than the list length.

Input & Output

example_1.py — Basic Rotation
$ Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
💡 Note: We rotate the list to the right by 2 places. The last 2 nodes (4,5) move to the front, and the rest (1,2,3) move to the back.
example_2.py — Single Rotation
$ Input: head = [0,1,2], k = 4
Output: [2,0,1]
💡 Note: Since k=4 and list length is 3, we effectively rotate by 4%3=1 position. Only the last node (2) moves to the front.
example_3.py — Edge Case
$ Input: head = [1], k = 1
Output: [1]
💡 Note: With only one node, any rotation returns the same list since there's nowhere to move the node to.

Constraints

  • The number of nodes in the list is in the range [0, 500]
  • Each node's value is in the range [-100, 100]
  • 0 ≤ k ≤ 2 × 109
  • k can be much larger than the list length

Visualization

Tap to expand
Rotating [1,2,3,4,5] right by k=2Original:12345← Last k=2 nodesStep 1: Make Circular12345Step 2: Break at position 3 (length-k = 5-2)Walk 3 steps from head: 1→2→3, break after 3123✂️45New HeadResult: 4→5→1→2→345123Algorithm Summary:1. Count length = 5, make circular2. Effective rotation: k % length = 2 % 5 = 23. Walk (length - k) = 3 steps from head4. Break after node 3, new head = node 4Time: O(n), Space: O(1)
Understanding the Visualization
1
Form a Circle
Connect the last person to the first to form a circle
2
Count and Calculate
Count total people and calculate effective rotation (k % total)
3
Find Break Point
Walk (total - k) steps from the original start to find where to break
4
Break and Reform
Break the circle at the calculated point to get the new arrangement
Key Takeaway
🎯 Key Insight: Converting to a circular list eliminates the need for multiple traversals and naturally handles the modulo arithmetic for large k values.
Asked in
Microsoft 45 Amazon 38 Google 32 Meta 28
89.2K Views
High Frequency
~18 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen