You are given an array nums of length n. Rotating it by k moves the first k elements, in order, to the back: rotating [5, 6, 7, 8] by 1 gives [6, 7, 8, 5].
After a rotation, every element whose value is at most its new index earns one point. Find the k from 0 to n − 1 that earns the most points. If several k tie, return the smallest.
Example 1
Input: nums = [2, 3, 0, 1] Output: 2 Why: k = 2 gives [0, 1, 2, 3], where all 4 elements score
2 more examples and the constraints
Example 2
Input: nums = [1, 0, 2, 3] Output: 0 Why: k = 0 and k = 3 both score 3; take the smaller
Example 3
Input: nums = [3, 2, 4, 0, 1] Output: 2 Why: k = 2 gives [4, 0, 1, 3, 2] for 4 points; k = 3 ties
Constraints
- 1 ≤ n ≤ 100,000
- 0 ≤ nums[i] < n
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Score every rotationO(n²)
- Difference array of rangesO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 elements | Verdict |
|---|---|---|---|
| Score every rotation | O(n²) | Clear; far too slow | |
| Difference array of ranges | O(n) | Best; two linear passes |
n = length of nums.
Edge cases to test
- One element. [0] has only k = 0, and it scores, so the answer is 0.
- Every k ties. [0, 0, 0] scores 3 for every k; return 0.
- Value 0. It scores for every k: its run covers all of 0 to n − 1, and it wraps unless i = n − 1.
- Value n − 1. It scores only at the last position: exactly one k, namely
(i + 1) mod n. - Already sorted. [0, 1, 2, 3] scores 4 with k = 0, the best possible.
Common mistakes
- Using
>=when updating the best, which returns the largest tied k instead of the smallest. - Taking
(i − v) % nin Java, C++ or TypeScript without adding n first, which can be negative. - Forgetting to split a run that wraps, so the −1 lands before the +1.
How to talk through it
- 1Clarify. Which direction does a rotation go? Is the point rule value ≤ index? Smallest k on ties?
- 2Give the brute force. Score all n rotations with the
(k + j) % nindex: O(n²). - 3Flip the view. Each element scores on one run of k; derive its ends from i and v.
- 4Code the difference array. +1 and −1 per run, split wraps, then a running sum over k.
- 5Test out loud. Run Example 1, a single element and an all-tie array 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?