Skip to content

Commit 9423033

Browse files
solves #2855: Minimum Right Shifts to Sort the Array in java
1 parent e1bf8a3 commit 9423033

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -854,7 +854,7 @@
854854
| 2839 | [Check if Strings Can be Made Equal With Operations I](https://leetcode.com/problems/check-if-strings-can-be-made-equal-with-operations-i) | [![Java](assets/java.png)](src/CheckIfStringsCanBeMadeEqualWithOperationsI.java) | |
855855
| 2843 | [Count Symmetric Integers](https://leetcode.com/problems/count-symmetric-integers) | [![Java](assets/java.png)](src/CountSymmetricIntegers.java) | |
856856
| 2848 | [Points That Intersect With Cars](https://leetcode.com/problems/points-that-intersect-with-cars) | [![Java](assets/java.png)](src/PointsThatIntersectWithCars.java) | |
857-
| 2855 | [Minimum Right Shifts to Sort the Array](https://leetcode.com/problems/minimum-right-shifts-to-sort-the-array) | | |
857+
| 2855 | [Minimum Right Shifts to Sort the Array](https://leetcode.com/problems/minimum-right-shifts-to-sort-the-array) | [![Java](assets/java.png)](src/MinimumRightShiftsToSortTheArray.java) | |
858858
| 2859 | [Sum of Values at Indices With K Set Bits](https://leetcode.com/problems/sum-of-values-at-indices-with-k-set-bits) | | |
859859
| 2833 | [Furthest Point From Origin](https://leetcode.com/problems/furthest-point-from-origin) | | |
860860
| 2839 | [Check if Strings Can be Made Equal With Operations I](https://leetcode.com/problems/check-if-strings-can-be-made-equal-with-operations-i) | | |
+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// https://leetcode.com/problems/minimum-right-shifts-to-sort-the-array
2+
// T: O(N)
3+
// S: O(1)
4+
5+
import java.util.List;
6+
7+
public class MinimumRightShiftsToSortTheArray {
8+
public int minimumRightShifts(List<Integer> array) {
9+
final int minElementIndex = getMinElementIndex(array);
10+
if (!canSort(array, minElementIndex)) {
11+
return -1;
12+
}
13+
14+
return (array.size() - minElementIndex) % array.size();
15+
}
16+
17+
private static boolean canSort(List<Integer> array, int minElementIndex) {
18+
for (int i = (minElementIndex + 1) % array.size(), k = 0 ; k < array.size() - 1; k++, i = (i + 1) % array.size()) {
19+
if (array.get(i) <= array.get((i - 1 + array.size()) % array.size())) {
20+
return false;
21+
}
22+
}
23+
return true;
24+
}
25+
26+
private static int getMinElementIndex(List<Integer> array) {
27+
int minElement = Integer.MAX_VALUE, index = -1;
28+
for (int i = 0 ; i < array.size() ; i++) {
29+
if (array.get(i) < minElement) {
30+
minElement = array.get(i);
31+
index = i;
32+
}
33+
}
34+
return index;
35+
}
36+
}

0 commit comments

Comments
 (0)