Rotate List - Problem

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

When we rotate to the right by k places, the last k nodes from the end become the first k nodes at the beginning, and the remaining nodes shift to the right.

Example: If we have list 1→2→3→4→5 and rotate by 2 places, the result is 4→5→1→2→3. The last 2 nodes (4,5) moved to the front.

Input & Output

Example 1 — Basic Rotation
$ Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
💡 Note: Rotating right by 2 means the last 2 nodes (4,5) move to the front: 1→2→3→4→5 becomes 4→5→1→2→3
Example 2 — Single Rotation
$ Input: head = [0,1,2], k = 4
Output: [2,0,1]
💡 Note: k=4 with length=3, so effective rotation is 4%3=1. Move last node to front: 0→1→2 becomes 2→0→1
Example 3 — No Rotation Needed
$ Input: head = [1], k = 1
Output: [1]
💡 Note: Single node list remains unchanged regardless of k value

Constraints

  • The number of nodes in the list is in the range [0, 500]
  • -100 ≤ Node.val ≤ 100
  • 0 ≤ k ≤ 2×109

Visualization

Tap to expand
Rotate List - Connect and Break Approach INPUT Original Linked List: 1 2 3 4 5 head = [1,2,3,4,5] k = 2 Rotate right by 2 places Length n = 5 Effective k = 2 % 5 = 2 Break at position: n-k = 3 (after node 3) ALGORITHM STEPS 1 Find Length Traverse to get n=5 2 Make Circular Connect tail(5) to head(1) 1 2 3 4 5 3 Find Break Point Move (n-k)=3 from head Break here! 4 Break Connection Set node3.next = null New head = node4 FINAL RESULT Rotated Linked List: 4 5 1 2 3 NULL Output: [4, 5, 1, 2, 3] Verification: Last 2 nodes (4,5) moved to front OK Key Insight: Instead of rotating k times, make the list circular by connecting tail to head. Then find the new tail at position (n - k % n) from head, set new head as next node, and break the circular connection. Time: O(n) | Space: O(1) - Single pass to find length, another to find break point. TutorialsPoint - Rotate List | Connect and Break Approach
Asked in
Google 42 Amazon 38 Microsoft 25 Facebook 22
892.0K Views
Medium Frequency
~25 min Avg. Time
8.4K 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