Leetcode 2855. Minimum Right Shifts to Sort the Array
You are given a 0-indexed array nums
of length n
. The array might be rotated to the right by any number of positions. The task is to find the minimum number of right shifts required to sort the array. A right shift consists of removing the last element of the array and adding it to the beginning.
If the array cannot be sorted using any number of right shifts, return -1
.
Input: nums = [3, 4, 5, 1, 2]
Output: 3
Explanation: After shifting right three times, nums becomes [1, 2, 3, 4, 5].
n
?
nums
?
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int minimumRightShifts(vector<int>& nums) {
int n = nums.size();
// Check if the array is already sorted.
if (is_sorted(nums.begin(), nums.end())) return 0;
// Identify the point of rotation.
for (int i = 0; i < n; ++i) {
vector<int> shifted = nums;
// Perform the right shift operation.
rotate(shifted.rbegin(), shifted.rbegin() + i, shifted.rend());
// Check if the resultant array is sorted.
if (is_sorted(shifted.begin(), shifted.end())) {
return i;
}
}
// If no valid right shift rotation sorts the array, return -1.
return -1;
}
};
int main() {
Solution sol;
vector<int> nums = {3, 4, 5, 1, 2};
int result = sol.minimumRightShifts(nums);
// Expected output: 3
return 0;
}
Given the rotate
and is_sorted
operations, and iterating for potentially all n
indices:
The solution involves checking each possible right shift to determine if it results in a sorted array. It ensures an optimal and simple approach to identifying the necessary rotations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?