Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #798: Smallest Rotation with Highest Score

In this guide, we solve Leetcode #798 Smallest Rotation with Highest Score in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Array, Prefix Sum

Intuition

Range queries become simple once we precompute cumulative sums.

We can transform subarray conditions into prefix comparisons.

Approach

Compute prefix sums and use a map to find matching prefixes.

This avoids nested loops while keeping the logic clear.

Steps:

  • Compute prefix sums.
  • Use a map to find valid ranges.
  • Update the answer.

Example

Input: nums = [2,3,1,4,0] Output: 3 Explanation: Scores for each k are listed below: k = 0, nums = [2,3,1,4,0], score 2 k = 1, nums = [3,1,4,0,2], score 3 k = 2, nums = [1,4,0,2,3], score 3 k = 3, nums = [4,0,2,3,1], score 4 k = 4, nums = [0,2,3,1,4], score 3 So we should choose k = 3, which has the highest score.

Python Solution

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

The time complexity is O(n). The space complexity is O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy