Smallest Rotation with Highest Score — LeetCode 798 Python Solution

HardArrayPrefix Sum
Problem
#798
Pattern
Prefix Sum
Reading time
3 min

The 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], ...

Example

Input
nums = [2,3,1,4,0]
Output
3
Explanation
Scores for each k are listed below:

Python solution

Python
class Solution:
    def bestRotation(self, nums: List[int]) -> int:
        n = len(nums)
        mx, ans = -1, n
        d = [0] * n
        for i, v in enumerate(nums):
            l, r = (i + 1) % n, (n + i + 1 - v) % n
            d[l] += 1
            d[r] -= 1
        s = 0
        for k, t in enumerate(d):
            s += t
            if s > mx:
                mx = s
                ans = k
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 798. Smallest Rotation with Highest Score is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 798. Smallest Rotation with Highest Score?
LeetCode 798. Smallest Rotation with Highest Score is rated Hard on LeetCode.
What is the time complexity of LeetCode 798. Smallest Rotation with Highest Score?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 798. Smallest Rotation with Highest Score?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 798. Smallest Rotation with Highest Score cover?
LeetCode 798. Smallest Rotation with Highest Score is tagged Array and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview