# Almost Sorted HackerRank Solution in C, C++, Java, Python

Given an array of integers, determine whether the array can be sorted in ascending order using only one of the following operations one time.

1. Swap two elements.
2. Reverse one sub-segment.

Determine whether one, both or neither of the operations will complete the task. If both work, choose swap. For instance, given an array [2,3,5,4] either swap the 4 and 5, or reverse them to sort the array. Choose swap. The Output Format section below details requirements.

Function Description

Complete the almostSorted function in the editor below. It should print the results and return nothing.

almostSorted has the following parameter(s):

arr: an array of integers

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.

Output Format

If the array is already sorted, output yes on the first line. You do not need to output anything else.

2. 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 and ending at index , 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

```2
4 2```

Sample Output 1

```yes
swap 1 2```

## Almost Sorted HackerRank 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");
}```

## Almost Sorted HackerRank Solution in C++

```#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;
}```

## Almost Sorted HackerRank 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 PrintWriter out;

public static void main(String[] args) throws IOException {
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);
}

final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;

din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
}

public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
}

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;
while (c <= ' ')
boolean neg = (c == '-');
if (neg)
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;
while (c <= ' ')
boolean neg = (c == '-');
if (neg)
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;
while (c <= ' ')
boolean neg = (c == '-');
if (neg)
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 {
buffer[0] = -1;
}

private byte read() throws IOException {
fillBuffer();
return buffer[bufferPointer++];
}

public void close() throws IOException {
if (din == null)
return;
din.close();
}
}

}```

## Almost Sorted HackerRank 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'```

## Almost Sorted HackerRank Solution in C#

```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AlmostSorted
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[n];

for (int i = 0; i < n; i++)
{
arr[i] = int.Parse(split[i]);
}

int s = 1;
while (s < n && arr[s] >= arr[s - 1])
{
s++;
}

if (s == n)
{
Console.WriteLine("yes");
return;
}

int e = n - 2;
while (e >= 0 && arr[e] <= arr[e + 1])
{
e--;
}

s--;
e++;

// Lets try swapping
int temp = arr[s];
arr[s] = arr[e];
arr[e] = temp;

if (s > 0 && arr[s] < arr[s - 1])
{
Console.WriteLine("no");
return;
}

if (e < n - 1 && arr[e] > arr[e + 1])
{
Console.WriteLine("no");
return;
}

// Is it assending from s to e?
bool isAscending = true;
for (int i = s + 1; i <= e; i++)
{
if (arr[i] < arr[i - 1])
{
isAscending = false;
break;
}
}

if (isAscending)
{
Console.WriteLine("yes");
Console.WriteLine("swap {0} {1}", s+1, e+1);
return;
}

// Lets try reverse
temp = arr[s];
arr[s] = arr[e];
arr[e] = temp;

isAscending = true;
for (int i = e - 1; i >= s; i--)
{
if (arr[i] < arr[i + 1])
{
isAscending = false;
break;
}
}

if (isAscending)
{
Console.WriteLine("yes");
Console.WriteLine("reverse {0} {1}", s + 1, e + 1);
return;
}

Console.WriteLine("no");
}
}
}```

Attempt Almost Sorted HackerRank  Challenge

Next HackerRank Challenge Solution