#798

Smallest Rotation with Highest Score

Hard
ArrayPrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of recalculating the score from scratch for each rotation, we can use a clever observation about how scores change as we rotate the array. We can maintain a score array that tracks the score changes efficiently.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an array to keep track of score changes for each rotation.
  2. 2Step 2: For each element in nums, determine how it affects the score for each possible rotation.
  3. 3Step 3: Calculate the cumulative score for each rotation using the score change array.
  4. 4Step 4: Find the rotation with the maximum score and return its index.
solution.py20 lines
1# Full working Python code
2
3def bestRotation(nums):
4    n = len(nums)
5    score = [0] * n
6    for i in range(n):
7        left = (i - nums[i] + 1 + n) % n
8        right = (i + 1) % n
9        score[left] += 1
10        if right != left:
11            score[right] -= 1
12    max_score = 0
13    best_k = 0
14    current_score = 0
15    for k in range(n):
16        current_score += score[k]
17        if current_score > max_score:
18            max_score = current_score
19            best_k = k
20    return best_k

Complexity note: The time complexity is O(n) because we only loop through the array a constant number of times, and the space complexity is O(n) due to the score array used to track score changes.

  • 1The score for each rotation can be efficiently calculated using a score change array.
  • 2The optimal solution leverages cumulative sums to avoid recalculating scores from scratch.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.