Smallest Rotation with Highest Score - Problem

You are given an array nums. You can rotate it by a non-negative integer k so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]].

Afterward, any entries that are less than or equal to their index are worth one point.

For example, if we have nums = [2,4,1,3,0], and we rotate by k = 2, it becomes [1,3,0,2,4]. This is worth 3 points because:

  • 1 > 0 [no points]
  • 3 > 1 [no points]
  • 0 ≤ 2 [one point]
  • 2 ≤ 3 [one point]
  • 4 ≤ 4 [one point]

Return the rotation index k that corresponds to the highest score we can achieve if we rotated nums by it. If there are multiple answers, return the smallest such index k.

Input & Output

Example 1 — Basic Rotation
$ Input: nums = [2,4,1,3,0]
Output: 3
💡 Note: Rotating by k=3 gives [3,0,2,4,1]. Score: 3>0 (no), 0≤1 (yes), 2≤2 (yes), 4>3 (no), 1≤4 (yes) = 3 points. This is optimal.
Example 2 — Multiple Optimal Solutions
$ Input: nums = [1,3,0,2,4]
Output: 0
💡 Note: No rotation needed. Score: 1>0 (no), 3>1 (no), 0≤2 (yes), 2≤3 (yes), 4≤4 (yes) = 3 points. This equals other rotations but k=0 is smallest.
Example 3 — Edge Case Small Array
$ Input: nums = [1,1]
Output: 1
💡 Note: k=0: [1,1] scores 1 point (1≤1). k=1: [1,1] scores 1 point (1≤1). Both equal, return k=1 since it's the only other option.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] < nums.length

Visualization

Tap to expand
Smallest Rotation with Highest Score INPUT nums = [2, 4, 1, 3, 0] 2 i=0 4 i=1 1 i=2 3 i=3 0 i=4 Score: nums[i] <= i gets 1 point Example Rotations: k=0: [2,4,1,3,0] score=2 k=1: [4,1,3,0,2] score=1 k=2: [1,3,0,2,4] score=2 k=3: [3,0,2,4,1] score=3 k=4: [0,2,4,1,3] score=2 ALGORITHM STEPS 1 Difference Array Track score changes per k 2 Find Valid Ranges For each nums[i], find k range 3 Mark +1/-1 Boundaries diff[start]++, diff[end+1]-- 4 Prefix Sum Scan Find k with max score Difference Array Technique 0 1 0 3 0 k=0 k=1 k=2 k=3 k=4 Max at k=3 (score=3) FINAL RESULT Array after k=3 rotation: 3 3>0 X 0 0<=1 OK 2 2<=2 OK 4 4>3 X 1 1<=4 OK Score = 3 points (highest) OUTPUT k = 3 Smallest k with max score Complexity Time: O(n) Space: O(n) Key Insight: Instead of simulating all n rotations (O(n^2)), use a difference array to track score changes. For each element, calculate the range of k values where it contributes a point, then mark boundaries in diff array. Prefix sum gives scores for all k values in O(n) total time. TutorialsPoint - Smallest Rotation with Highest Score | Optimal Solution
Asked in
Google 15 Facebook 8
28.5K Views
Medium Frequency
~35 min Avg. Time
847 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