814. Smallest Rotation with Highest Score
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find the best rotation k of an array nums that maximizes a score. The score is the number of elements A[i] in the rotated array A that are less than or equal to their index i. If multiple k values yield the same maximum score, we must return the smallest such k. A brute-force approach of trying every rotation k and calculating the score for each would be O(n^2), which is too slow given that n can be up to 10^5. A more efficient approach is needed.
Solution
Smallest Rotation with Highest Score in Python
class Solution:
def bestRotation(self, nums: List[int]) -> int:
n = len(nums)
# diff[k] will store the change in the number of lost points at rotation k.
# A point is lost if nums[j] > new_index.
diff = [0] * n
for j, v in enumerate(nums):
# The new index i for nums[j] after rotation k is (j - k + n) % n.
# We lose a point if v > i, i.e., i is in [0, v-1].
# For each such i, the corresponding k is (j - i + n) % n.
# This creates a range of "bad" k's.
# start of bad k's (for i=v-1): (j - (v-1) + n) % n
# end of bad k's (for i=0): (j - 0 + n) % n = j
start = (j - v + 1 + n) % n
end = j
if start <= end:
# The bad range is a single interval [start, end].
# Increment loss count for this range.
diff[start] += 1
if end + 1 < n:
diff[end + 1] -= 1
else:
# The bad range wraps around: [start, n-1] and [0, end].
# This means loss increases for all k, so we add 1 at the beginning.
diff[0] += 1
# And handle the two intervals.
# For [0, end], the effect ends at end+1.
if end + 1 < n:
diff[end + 1] -= 1
# For [start, n-1], the effect starts at start.
diff[start] += 1
max_score = -1
best_k = 0
current_loss = 0
# Compute the loss for each k using the difference array and find the best k.
for k in range(n):
current_loss += diff[k]
current_score = n - current_loss
if current_score > max_score:
max_score = current_score
best_k = k
return best_k
Smallest Rotation with Highest Score in Java
class Solution {
public int bestRotation(int[] nums) {
int n = nums.length;
// diff[k] stores the change in the number of lost points when moving from rotation k-1 to k.
int[] diff = new int[n];
for (int j = 0; j < n; j++) {
int v = nums[j];
// An element nums[j] at original index j loses a point if its new index i is less than its value v.
// new_index i = (j - k + n) % n.
// Lost point condition: v > (j - k + n) % n.
// This means (j - k + n) % n is in [0, v-1].
// This corresponds to a range of "bad" k's.
// The start of the bad range for k is when new_index is v-1.
// k_start corresponds to i = v-1: k = (j-(v-1)+n)%n = (j-v+1+n)%n
// The end of the bad range for k is when new_index is 0.
// k_end corresponds to i = 0: k = (j-0+n)%n = j
int start = (j - v + 1 + n) % n;
int end = j;
if (start <= end) {
// The bad range is [start, end]. Increment loss count for this range.
diff[start]++;
if (end + 1 < n) {
diff[end + 1]--;
}
} else {
// The bad range wraps around: [start, n-1] and [0, end].
// Handle as two ranges.
// Range [0, end]:
diff[0]++;
if (end + 1 < n) {
diff[end + 1]--;
}
// Range [start, n-1]:
diff[start]++;
}
}
int maxScore = -1;
int bestK = 0;
int currentLoss = 0;
// Calculate total loss for each k and find the one with minimum loss (max score).
for (int k = 0; k < n; k++) {
currentLoss += diff[k];
int currentScore = n - currentLoss;
if (currentScore > maxScore) {
maxScore = currentScore;
bestK = k;
}
}
return bestK;
}
}
Smallest Rotation with Highest Score in C++
class Solution {
public:
int bestRotation(vector<int>& nums) {
int n = nums.size();
// diff[k] stores the change in the number of lost points when moving from rotation k-1 to k.
vector<int> diff(n, 0);
for (int j = 0; j < n; ++j) {
int v = nums[j];
// An element nums[j] at original index j loses a point if its new index i is less than its value v.
// new_index i = (j - k + n) % n.
// Lost point condition: v > (j - k + n) % n.
// This means (j - k + n) % n is in [0, v-1].
// For each losing i in [0, v-1], we find the corresponding k = (j - i + n) % n.
// This gives a range of "bad" k's.
// Let i = v-1, k_low_bound = (j - (v-1) + n) % n = (j - v + 1 + n) % n.
// Let i = 0, k_high_bound = (j - 0 + n) % n = j.
// So, bad k's are in a range from start to end (modulo n).
int start = (j - v + 1 + n) % n;
int end = j;
if (start <= end) {
// The bad range is [start, end].
// Increment loss count for this range.
diff[start]++;
if (end + 1 < n) {
diff[end + 1]--;
}
} else {
// The bad range wraps around: [start, n-1] and [0, end].
// Increment for [0, n-1] (effectively).
diff[0]++;
// Then handle the two ranges.
// For [0, end], decrement at end+1.
if (end + 1 < n) {
diff[end + 1]--;
}
// For [start, n-1], increment at start.
diff[start]++;
}
}
int max_score = -1;
int best_k = 0;
int current_loss = 0;
for (int k = 0; k < n; ++k) {
current_loss += diff[k];
int current_score = n - current_loss;
if (current_score > max_score) {
max_score = current_score;
best_k = k;
}
}
return best_k;
}
};
Smallest Rotation with Highest Score in TypeScript
function bestRotation(nums: number[]): number {
const n = nums.length;
// diff[k] stores the change in the number of lost points when moving from rotation k-1 to k.
const diff = new Array(n).fill(0);
for (let j = 0; j < n; j++) {
const v = nums[j];
// An element nums[j] at original index j loses a point if its new index i is less than its value v.
// new_index i = (j - k + n) % n.
// Lost point condition: v > (j - k + n) % n.
// This means (j - k + n) % n is in [0, v-1].
// This corresponds to a range of "bad" k's.
// The start of the bad range for k is when new_index is v-1.
// k_start corresponds to i = v-1: k = (j-(v-1)+n)%n = (j-v+1+n)%n
// The end of the bad range for k is when new_index is 0.
// k_end corresponds to i = 0: k = (j-0+n)%n = j
const start = (j - v + 1 + n) % n;
const end = j;
if (start <= end) {
// The bad range is [start, end]. Increment loss count for this range.
diff[start]++;
if (end + 1 < n) {
diff[end + 1]--;
}
} else {
// The bad range wraps around: [start, n-1] and [0, end].
// Handle as two ranges.
// Range [0, end]:
diff[0]++;
if (end + 1 < n) {
diff[end + 1]--;
}
// Range [start, n-1]:
diff[start]++;
}
}
let maxScore = -1;
let bestK = 0;
let currentLoss = 0;
// Calculate total loss for each k and find the one with minimum loss (max score).
for (let k = 0; k < n; k++) {
currentLoss += diff[k];
const currentScore = n - currentLoss;
if (currentScore > maxScore) {
maxScore = currentScore;
bestK = k;
}
}
return bestK;
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.