We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Check if array is sorted and print relevant output if yes.
If no, assume it' partly sorted.
Look from left to right for decreasing sequence, store start in i.
Look from right to left for decreasing sequence, store end in j.
Swap & check if sorted, print relevant output.
If unsorted, reverse remaining elements between i & j.
Check again, print relevant output.
public class Solution {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
if (n < 2) System.out.println("yes");
int[] d = new int[n];
for (int i = 0; i < n; d[i++] = s.nextInt());
if (isAsc(d)) {
System.out.println("yes");
return;
}
int i, j;
for (i = 0; i < n - 1 && d[i] < d[i+1]; ++i);
for (j = n-1; j > 0 && d[j-1] < d[j]; --j);
// try swap
swap(d, i, j);
if (isAsc(d)) {
System.out.println("yes\nswap "+ (i+1) + " " + (j+1));
return;
}
// try reverse (continue reversing inner pairs)
int k = i+1, l = j-1;
while (k < l) swap(d, k++, l--);
if (isAsc(d)) {
System.out.println("yes\nreverse " + (i+1) + " " + (j+1));
return;
}
System.out.println("no");
}
public static void swap(int[] d, int i, int j) {
int tmp = d[i];
d[i] = d[j];
d[j] = tmp;
}
public static boolean isAsc(int[] d) {
for (int i = 0; i < d.length-1; ++i) {
if (d[i] > d[i+1]) return false;
}
return true;
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Almost Sorted
You are viewing a single comment's thread. Return to all comments →
My solution in O(n):
public class Solution {
}