HackerRank Almost Sorted Solution

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.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

HackerRank Almost Sorted Solution
HackerRank Almost Sorted Solution

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

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.

  1. Swap two elements.
  2. Reverse one subsegment.

Determine whether one, both or neither of the operations will complete the task. Output is as follows.

  1. 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:
    • 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.

  1. 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 spaceseparated integers arr[i] where 1 <= i <= n.

Constraints

  • 2 <= n <= 100000
  • 0 <= arr[i] <= 1000000
  • All arr[i] are distinct.

Output Format

  1. 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 l and ending at index r, both inclusive.

If an array can be sorted by either swapping or reversing, choose swap.

  1. 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

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");
}

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

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();
    }
  }

}

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'

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);
});

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)
    }
}

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.

FAQ:

1. How do you solve the first question in HackerRank?

If you want to solve the first question of Hackerrank then you have to decide which programing language you want to practice i.e C programming, Cpp Programing, or Java programming then you have to start with the first program HELLO WORLD.

2. How do I find my HackerRank ID?

You will receive an email from HackerRank to confirm your access to the ID. Once you have confirmed your email, the entry will show up as verified on the settings page. You will also have an option to “Make primary”. Click on that option. Read more

3. Does HackerRank detect cheating?

yes, HackerRank uses a powerful tool to detect plagiarism in the candidates’ submitted code. The Test report of a candidate highlights any plagiarized portions in the submitted code and helps evaluators to verify the integrity of answers provided in the Test.

4. Does HackerRank use camera?

No for coding practice Hackerrank does not use camera but for companies’ interviews code submission time Hackerrank uses the camera.

5. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume. 

6. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite. 

7. What is HackerRank?

HackerRank is a tech company that focuses on competitive programming challenges for both consumers and businesses. Developers compete by writing programs according to provided specifications. Wikipedi


Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Please share our posts on social media platforms and also suggest to your friends to Join Our Groups. Don’t forget to subscribe. 

Sharing Is Caring

Leave a Comment