Smallest Rotation with Highest Score - Problem

You are given an array nums and need to find the optimal rotation that maximizes your score!

How rotation works: When you rotate the array by k positions, it becomes [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]

How scoring works: After rotation, you get 1 point for each element where nums[i] ≤ i (value ≤ index)

Goal: Return the smallest rotation index k that gives you the highest possible score.

Example: With nums = [2,4,1,3,0] and rotation k = 2:

  • Array becomes: [1,3,0,2,4]
  • Score calculation: 1 > 0 ❌, 3 > 1 ❌, 0 ≤ 2 ✅, 2 ≤ 3 ✅, 4 ≤ 4
  • Total score: 3 points

Input & Output

example_1.py — Basic Rotation
$ Input: nums = [2,4,1,3,0]
Output: 2
💡 Note: Rotation by k=2 gives [1,3,0,2,4] with score 3 (positions 2,3,4 satisfy condition). This is the maximum possible score.
example_2.py — All Elements Large
$ Input: nums = [1,3,0,2,4]
Output: 0
💡 Note: No rotation needed. At k=0, we get score 3 from positions 2,3,4. This is already optimal.
example_3.py — Single Element
$ Input: nums = [5]
Output: 0
💡 Note: With only one element, k=0 is the only option. Element 5 > index 0, so score is 0.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] < nums.length
  • The optimal solution must handle large arrays efficiently

Visualization

Tap to expand
02431Rotation k=2Score: 3🎡 Green seats = Happy passengers (value ≤ seat#)🎯 Goal: Find rotation with most green seats
Understanding the Visualization
1
Analyze Passenger Preferences
Each passenger has a satisfaction threshold - they're happy if seat number ≥ their requirement
2
Calculate Contribution Ranges
For each passenger, determine which wheel rotations would satisfy them
3
Track Score Changes
Use differential tracking to see how satisfaction changes with each rotation
4
Find Optimal Position
The rotation with maximum satisfied passengers wins!
Key Takeaway
🎯 Key Insight: Rather than simulating every rotation, we mathematically analyze when each element contributes to the score and use differential arrays to efficiently compute all rotation scores in linear time.
Asked in
Google 15 Meta 8 Apple 5 Microsoft 3
23.5K Views
Medium Frequency
~35 min Avg. Time
892 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