You get the head of a singly linked list and a number k. Rotate the list to the right k times. One rotation takes the last node off the end and makes it the new first node.
Return the head of the rotated list. k can be far larger than the length of the list.
Example 1
Input: head = [6, 2, 9, 4, 1], k = 7 Output: [4, 1, 6, 2, 9] Why: 7 turns on 5 nodes equal 2 turns
2 more examples and the constraints
Example 2
Input: head = [3, 8], k = 1 Output: [8, 3] Why: one turn moves 8 to the front
Example 3
Input: head = [], k = 5 Output: [] Why: an empty list stays empty
Constraints
- The list has between 0 and 500 nodes
- Each node value is from −100 up to 100
- k is at least 0 and at most 2,000,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- One turn at a timeO(n²)
- Close a ring, cut onceO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Steps for 500 nodes | Verdict |
|---|---|---|---|
| One turn at a time | O(n²) | Passes here; slow | |
| Close a ring, cut once | O(n) | Best |
n = number of nodes. Both reduce k with k % n first.
Edge cases to test
- Empty list. Return null right away;
k % 0would crash. - k is a multiple of n. [1, 2, 3, 4] with k = 4 comes back unchanged.
- One node. [42] with any k is still [42]; the ring is the node pointing at itself, cut right away.
- Huge k. k = 2,000,000,000 must be reduced with % n before any walking.
Common mistakes
- Forgetting
k % n, so a large k loops billions of times. - Taking
k % nbefore checking for an empty list, which divides by zero. - Leaving the ring closed, so the returned list never ends.
How to talk through it
- 1Clarify. Can the list be empty? Can k be larger than the length? Rotate right means the tail moves to the front?
- 2Reduce k. n turns bring the list back, so only k % n turns matter.
- 3Give the simple answer. Move the tail to the front k % n times. O(n²) because each turn walks the list.
- 4Cut in one place. The answer is the same chain cut elsewhere: join tail to head, step n − k from the tail, cut after it.
- 5Test out loud. Run the empty list, k = 0, k = n and a single node before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?