Hello Programmers, In this post, you will learn how to solve HackerRank Almost Sorted Solution. This problem is a part of the HackerRank Algorithms Series.
One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

HackerRank Almost Sorted
Task
Given an array of integers, determine whether the array can be sorted in ascending order using only one of the following operations one time.
- Swap two elements.
- Reverse one sub–segment.
Determine whether one, both or neither of the operations will complete the task. Output is as follows.
- If the array is already sorted, output yes on the first line. You do not need to output anything else.
- If you can sort this array using one single operation (from the two permitted operations) then output yes on the first line and then:
- If elements can only be swapped, d[l] and d[r], output swap l r in the second line. l and r are the indices of the elements to be swapped, assuming that the array is indexed from 1 to n.
- If elements can only be reversed, for the segment d[l . . . r], output reverse l r in the second line. l and r are the indices of the first and last elements of the subarray to be reversed, assuming that the array is indexed from 1 to n. Here d[l . . . r] represents the subarray that begins at index l and ends at index r, both inclusive.
If an array can be sorted both ways, by using either swap or reverse, choose swap.
- If the array cannot be sorted either way, output no on the first line.
Example
arr = [2, 3, 5, 4]
Either swap the 4 and 5 at indices 3 and 4, or reverse them to sort the array. As mentioned above, swap is preferred over reverse. Choose swap. On the first line, print yes
. On the second line, print swap 3 4
.
Function Description
Complete the almostSorted function in the editor below.
almostSorted has the following parameter(s):
- int arr[n]: an array of integers
Prints
- Print the results as described and return nothing.
Input Format
The first line contains a single integer n, the size of arr.
The next line contains n space–separated integers arr[i] where 1 <= i <= n.
Constraints
- 2 <= n <= 100000
- 0 <= arr[i] <= 1000000
- All arr[i] are distinct.
Output Format
- If the array is already sorted, output yes on the first line. You do not need to output anything else.
- If you can sort this array using one single operation (from the two permitted operations) then output yes on the first line and then:
a. If elements can be swapped, d[l] and d[r], output swap l r in the second line. l and r are the indices of the elements to be swapped, assuming that the array is indexed from 1 to n.
b. Otherwise, when reversing the segment d[l . . . r], output reverse l r in the second line. l and r are the indices of the first and last elements of the subsequence to be reversed, assuming that the array is indexed from 1 to n.
d[l . . . r]represents the sub-sequence of the array, beginning at index l and ending at index r, both inclusive.
If an array can be sorted by either swapping or reversing, choose swap.
- If you cannot sort the array either way, output no on the first line.
Sample Input 1
STDIN Function ----- -------- 2 arr[] size n = 2 4 2 arr = [4, 2]
Sample Output 1
yes
swap 1 2
Explanation 1
You can either swap(1, 2) or reverse(1, 2). You prefer swap.
Sample Input 2
3
3 1 2
Sample Output 2
no
Explanation 2
It is impossible to sort by one single operation.
Sample Input 3
6
1 5 4 3 2 6
Sample Output 3
yes
reverse 2 5
Explanation 3
You can reverse the sub-array d[2…5] = “5 4 3 2”, then the array becomes sorted.
HackerRank Almost Sorted Solution
HackerRank Almost Sorted Solution in C
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <limits.h> int n; int v[100002]; int l, r; int issorted() { for (int i = 1; i <= n; i++) if (v[i-1] > v[i]) return 0; return 1; } int testreverse() { int i; int first; for (i = 1; i <= n; i++) { if (v[i-1] > v[i]) { first = i; break; } } if (i == n+1) return 0; // sorted! int second; for (i = first+1; i <= n; i++) { if (v[i-1] < v[i]) { second = i; break; } } if (i == n+1) { l = first - 1; r = n; return (v[n] >= v[first-2]); } // Rest sorted? for (i = second+1; i <= n; i++) { if (v[i-1] > v[i]) return 0; } l = first - 1; r = second - 1; return (v[first-1] <= v[second] && v[second-1] >= v[first-2]); } int testswap() { int i; int first; for (i = 1; i <= n; i++) { if (v[i-1] > v[i]) { first = i; break; } } if (i == n+1) return 0; // sorted! if (v[first-2] > v[first]) { return 0; } int second; for (i = first+1; i <= n; i++) { if (v[i-1] > v[i]) { second = i; break; } } if (i == n+1) { return 0; } // Rest sorted? for (i = second+1; i <= n; i++) { if (v[i-1] > v[i]) return 0; } // l = first - 1; // r = second - 1; // return (v[first-1] <= v[second] && v[second-1] >= v[first-2]); l = first - 1; r = second; return (v[l-1] <= v[r] && v[r] <= v[l+1] && v[r-1] <= v[l] && v[l] <= v[r+1]); } int main() { int stage = 0; scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &v[i+1]); v[0] = INT_MIN; v[n+1] = INT_MAX; int first; // Sorted? if (issorted()) { printf("yes\n"); return 0; } if (testreverse()) { int i; for (i = l; i < r; i++) if (v[l] != v[i]) break; if (i == r) printf("yes\nswap %d %d", l, r); else printf("yes\nreverse %d %d", l, r); return 0; } if (testswap()) { printf("yes\nswap %d %d", l, r); return 0; } printf("no"); }
HackerRank Almost Sorted Solution in Cpp
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <algorithm> #include <iostream> using namespace std; int N, v[100005], s[100005]; int main() { cin >> N; for(int i=0; i<N; i++){ cin >> v[i]; s[i] = v[i]; } sort(s, s+N); vector<int> diff; for(int i=0; i<N; i++) if(v[i] != s[i]) diff.push_back(i); if(diff.size() == 0){ cout << "yes" << endl; return 0; } if(diff.size() == 2 && s[diff[0]] == v[diff[1]] && s[diff[1]] == v[diff[0]]){ cout << "yes\nswap " << diff[0] + 1 << " " << diff[1] + 1 << endl; return 0; } reverse(v + diff[0], v + diff.back() + 1); bool good = true; for(int i=0; i<N; i++) good &= v[i] == s[i]; if(good) cout << "yes\nreverse " << diff[0] + 1 << " " << diff.back() + 1 << endl; else cout << "no" << endl; return 0; }
HackerRank Almost Sorted Solution in Java
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; public class Solution { private static Reader in; private static PrintWriter out; public static void main(String[] args) throws IOException { in = new Reader(); out = new PrintWriter(System.out, true); int N = in.nextInt(); int[] arr = new int[N]; for (int i = 0; i < N; i++) arr[i] = in.nextInt(); int[] brr = Arrays.copyOf(arr, N); Arrays.sort(brr); HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); for (int i = 0; i < N; i++) mp.put(brr[i], i); for (int i = 0; i < N; i++) { arr[i] = mp.get(arr[i]); } int outofpos = 0; for (int i = 0; i < N; i++) { if (arr[i] != i) outofpos++; } if (outofpos == 0) { out.println("yes"); out.close(); System.exit(0); } else if (outofpos == 2) { out.println("yes"); out.print("swap"); for (int i = 0; i < N; i++) { if (arr[i] != i) out.print(" " + (i + 1)); } out.println(); out.close(); System.exit(0); } else { int s = -1, e = -1; for (int i = 0; i < N; i++) { if (arr[i] != i) { e = i; if (s == -1) s = i; } } for (int i = s, j = e; i < j; i++, j--) { int t = arr[i]; arr[i] = arr[j]; arr[j] = t; } for (int i = 0; i < N; i++) { if (arr[i] != i) { out.println("no"); out.close(); System.exit(0); } } out.println("yes"); out.printf("reverse %d %d\n", s+1, e+1); out.close(); System.exit(0); } out.close(); System.exit(0); } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1024]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
HackerRank Almost Sorted Solution in Python
def mismatch(A): B = list(sorted(A)) return [i for i in xrange(len(A)) if A[i]!=B[i]] def swappable(A, indices): return len(indices)==2 def reversible(A, indices): minimum = min(indices) maximum = max(indices) B = A[minimum:maximum+1][::-1] if B == list(sorted(B)): return minimum,maximum return False N = int(raw_input()) A = [-1] + map(int, raw_input().split()) I = mismatch(A) if swappable(A,I): print "yes\nswap %d %d"%(I[0],I[1]) else: R = reversible(A,I) if R: print 'yes\nreverse %d %d'%(R[0],R[1]) else: print 'no'
HackerRank Almost Sorted Solution using JavaScript
function processData(input) { var lines = input.trim().split('\n').splice(1); process.stdout.write(lines.map(parseLine).join('\n')) } function parseLine(line) { var arr = line.split(' ').map(function(n){return parseInt(n)}), forward = true, outOfOrderIdx, outOfOrderEndIdx, isSwap = false; if (arr.length <= 1) return 'yes'; if (arr.length === 2) return {true: 'yes', false: 'yes\nswap 1 2'}[arr[0] < arr[1]]; for (var i = 1; i < arr.length; i++) { if (isSwap && !outOfOrderEndIdx && arr[outOfOrderIdx - 1] > arr[i] && arr[outOfOrderIdx - 1] > arr[i - 1] && arr[outOfOrderIdx - 1] < arr[i + 1]) { outOfOrderEndIdx = i + 1; } else if (arr[i - 1] < arr[i]) { if (!forward) { if (arr[outOfOrderIdx - 1] < arr[i]) { forward = true; outOfOrderEndIdx = i; } else { return 'no'; } } } else if (forward) { if (!outOfOrderIdx) { outOfOrderIdx = i; if (i < arr.length - 1 && arr[i - 1] > arr[i] && arr[i] > arr[i + 1]) { forward = false; } else if (i < arr.length - 1 && arr[i - 1] < arr[i + 1]) { isSwap = true; outOfOrderEndIdx = i + 1; } else { isSwap = true; } } else { return 'no'; } } } if (isSwap && !outOfOrderEndIdx) { return 'no'; } if (!outOfOrderEndIdx) { outOfOrderEndIdx = arr.length; } if (!outOfOrderIdx) { return 'yes'; } else if (isSwap || outOfOrderIdx + 1 === outOfOrderEndIdx) { return 'yes\nswap ' + outOfOrderIdx + ' ' + outOfOrderEndIdx; } else { return 'yes\nreverse ' + outOfOrderIdx + ' ' + outOfOrderEndIdx; } } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); });
HackerRank Almost Sorted Solution in Scala
import java.util.Scanner object Solution { def canSort(nums:List[Int]) { val firstNotSorted = isSorted(nums) if(firstNotSorted == -1) { println("yes") }else if(nums.size <= 2) { println("yes") println("swap 1 2") }else { val lastNotSorted: Int = finalNotSorted(nums) if(lastNotSorted == firstNotSorted || lastNotSorted == 0) { println("no") }else if(checkSlice(nums.slice(firstNotSorted,lastNotSorted + 1))) { println("yes") println("reverse " + firstNotSorted + " " + (lastNotSorted + 1)) }else if(nums(lastNotSorted) > nums(firstNotSorted - 2) && nums(firstNotSorted - 1) > nums(lastNotSorted - 1)){ println("yes") println("swap " + (firstNotSorted) + " " + (lastNotSorted + 1)) }else { println("no") } } } def checkSlice(slice:List[Int]): Boolean = { slice.sliding(2).forall(x => x(0) > x(1)) } def isSorted(nums:List[Int]): Int = { nums.sliding(2).indexWhere(x => x(0) > x(1)) + 1 } def finalNotSorted(nums:List[Int]): Int = { nums.sliding(2).toList.lastIndexWhere(x => x(0) > x(1)) + 1 } def main(args: Array[String]) { val in = new Scanner(System.in) val n = in.nextInt val nums = List.fill(n)(in.nextInt) canSort(nums) } }
HackerRank Almost Sorted Solution in Pascal
{$MACRO ON} {$MODE OBJFPC} {$COPERATORS ON} uses gvector,garrayutils; const fi=''; fo=''; type TType = int32; vector = specialize TVector<TType>; compare = class public class function c(a,b : TType) : boolean; end; utils = specialize TOrderingArrayUtils<vector,TType,compare>; class function compare.c(a,b : TType) : boolean; begin Result := a<b; end; var n : int32; a,b,c : vector; procedure readData(); var i,tmp : int32; begin readln(n); a := vector.Create(); b := vector.Create(); c := vector.Create(); for i := 0 to n-1 do begin read(tmp); a.PushBack(tmp); b.PushBack(tmp); end; end; procedure main(); var i,tmp : int32; l,r : int32; begin readData(); utils.Sort(b,n); for i := 0 to n-1 do if a[i]<>b[i] then c.PushBack(i); if c.Size() = 0 then begin write('yes'); end else if c.Size() = 2 then begin writeln('yes'); write('swap ',c[0]+1,#32,c[1]+1); end else begin l := c.Front(); r := c.Back(); while l<r do begin tmp := a[l]; a[l] := a[r]; a[r] := tmp; l+=1; r-=1; end; for i := 0 to n-1 do if a[i]<>b[i] then begin write('no'); { readln; readln; } halt; end; writeln('yes'); write('reverse ',c.Front()+1,#32,c.Back()+1); end; { readln; readln;} end; begin assign(input,fi); reset(input); assign(output,fo); rewrite(output); main(); close(input); close(output); end.
Disclaimer: This problem (Almost Sorted) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.