LeetCode 2855: Minimum Right Shifts to Sort the Array Solution
Master LeetCode problem 2855 (Minimum Right Shifts to Sort the Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2855. Minimum Right Shifts to Sort the Array
Problem Explanation
Explanation
To solve this problem, we can simulate the right shifts and check if the array becomes sorted at any point. We iterate through each element in the array and shift it to the right. After each shift, we check if the array is sorted. If it is sorted, we return the number of shifts. If we finish all shifts without finding a sorted array, we return -1.
-
Algorithm:
- Iterate through each element in the array.
- Perform a right shift operation by swapping elements.
- Check if the array is sorted after each shift.
- If the array is sorted, return the number of shifts.
- If no sorted array is found, return -1.
-
Time Complexity: O(n^2) where n is the number of elements in the input array.
-
Space Complexity: O(1)
Solution Code
class Solution {
public int minRightShifts(int[] nums) {
int n = nums.length;
int shifts = 0;
for (int i = 0; i < n; i++) {
boolean sorted = true;
for (int j = 0; j < n - 1; j++) {
if (nums[j] > nums[j + 1]) {
sorted = false;
int temp = nums[j];
nums[j] = nums[(j + 1) % n];
nums[(j + 1) % n] = temp;
}
}
if (sorted) {
return shifts;
}
shifts++;
}
return -1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2855 (Minimum Right Shifts to Sort the Array)?
This page provides optimized solutions for LeetCode problem 2855 (Minimum Right Shifts to Sort the Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2855 (Minimum Right Shifts to Sort the Array)?
The time complexity for LeetCode 2855 (Minimum Right Shifts to Sort the Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2855 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2855 in Java, C++, or Python.