Smallest Rotation with Highest Score

HardArrays & Hashingprefix sum

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an array nums of length n where 0 <= nums[i] < n. Rotating by k (for 0 <= k < n) moves the first k elements to the end, giving [nums[k], nums[k+1], ..., nums[n-1], nums[0], ..., nums[k-1]]. After rotation, each element that is **less than or equal to its new index** earns one point. The score of the rotation is the total number of points. Return the rotation k with the highest score. If several rotations tie, return the **smallest** such k. Aim for O(n) time.

Examples

Input: nums = [2,3,1,4,0]
Output: 3
Scores for k = 0..4 are 2, 3, 3, 4, 3. Rotating by 3 gives [4,0,2,3,1], where 0, 2, 3 and 1 each earn a point.
Input: nums = [1,3,0,2,4]
Output: 0
Every rotation scores 3, so the smallest k, 0, is returned.

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] < nums.length

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More prefix sum problems