Hackerrank Almost Sorted Solution

Hackerrank Almost Sorted Solution

.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue} .MathJax_SVG_LineBox {display: table!important} .MathJax_SVG_LineBox span {display: table-cell!important; width: 10000em!important; min-width: 0; max-width: none; padding: 0; border: 0; margin: 0}

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  either swap the  and , 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.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue} .MathJax_SVG_LineBox {display: table!important} .MathJax_SVG_LineBox span {display: table-cell!important; width: 10000em!important; min-width: 0; max-width: none; padding: 0; border: 0; margin: 0}

The first line contains a single integer , the size of .
The next line contains  space-separated integers  where .

Constraints.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue} .MathJax_SVG_LineBox {display: table!important} .MathJax_SVG_LineBox span {display: table-cell!important; width: 10000em!important; min-width: 0; max-width: none; padding: 0; border: 0; margin: 0}



All   are distinct.

Output Format.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue} .MathJax_SVG_LineBox {display: table!important} .MathJax_SVG_LineBox span {display: table-cell!important; width: 10000em!important; min-width: 0; max-width: none; padding: 0; border: 0; margin: 0}

  1. 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,  and , output swap l r in the second line.  and  are the indices of the elements to be swapped, assuming that the array is indexed from  to .

b. Otherwise, when reversing the segment , output reverse l r in the second line.  and  are the indices of the first and last elements of the subsequence to be reversed, assuming that the array is indexed from  to .

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.

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

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.

Solution in java8

Approach 1.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the almostSorted function below.
    static void almostSorted(int[] arr) {
        int count=0;
        int[] a=new int[arr.length];
        for(int i=0;i<arr.length;i++)
        {
            a[i]=arr[i];
        }
Arrays.sort(a);
int[] c=new int[arr.length];int j=0;
for(int i=0;i<arr.length;i++)
{
    if(a[i]!=arr[i]){
        c[j]=i;j++;
    count++;}
}

int k=j,count1=0;
if(count==2)
{
   
    System.out.println("yes");
    System.out.println("swap "+(c[0]+1)+" "+(c[1]+1));
}else 
{for(int i=0,l=k-1;(i<=k-1)&&(l>=0);i++,l--){
    if(arr[c[i]]==a[c[l]]){
count1++;
}}
if(count1==j){
System.out.println("yes");
System.out.println("reverse "+(c[0]+1)+" "+(c[j-1]+1));}
else
 System.out.println("no");
}

    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int n = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        int[] arr = new int[n];

        String[] arrItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < n; i++) {
            int arrItem = Integer.parseInt(arrItems[i]);
            arr[i] = arrItem;
        }

        almostSorted(arr);

        scanner.close();
    }
}

Approach 2.

import java.io.*;

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        // Get input
        final int N = Integer.parseInt(br.readLine());
        final int[] arr = new int[N];
        String[] line = br.readLine().split(" ");
        for (int i = 0; i < N; ++i) {
            arr[i] = Integer.parseInt(line[i]);
        }

        // Print output
        System.out.print(solve(arr, N));
    }

    private static String solve(final int[] A, final int N) {
        int l = 0;
        int r = N - 1;

        // Check for out of place index from the left
        while (l < r && A[l] <= A[l + 1]) {
            ++l;
        }

        // Check if array already sorted
        if (l == r) {
            return "yes";
        }

        // Check for out of place index from the right
        while (r > l && A[r] >= A[r - 1]) {
            --r;
        }

        // Check if swapping or reversing would NOT sort the array
        if ((l > 0 && A[r] < A[l - 1]) || (r < N - 1 && A[l] > A[r + 1])) {
            return "no";
        }

        // Check if we're dealing with a reversal
        int m;
        for (m = l + 1; m < r && A[m] >= A[m + 1]; ++m) {
        }
        if (m == r) {
            return "yes\n" + ((r - l < 2) ? "swap " : "reverse ") + (l + 1) + " " + (r + 1);
        }

        // Check if we're NOT dealing with a swap
        if (m - l > 1 || A[l] < A[r - 1] || A[r] > A[l + 1]) {
            return "no";
        }

        // Check if we're dealing with a swap
        for (int k = r - 1; m < k && A[m] <= A[m + 1]; ++m) {
        }
        return (r - m > 1) ? "no" : "yes\nswap " + (l + 1) + " " + (r + 1);
    }
}

Approach 3.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
import java.util.stream.Collectors;

public class Solution {

    // Complete the almostSorted function below.
    static void almostSorted(int[] arr) {

        int[] sortedArr = Arrays.stream(arr).sorted().toArray();
        if(arr.equals(sortedArr)){
            System.out.println("yes");
            return;
        }

        int count = 0;
        List<Integer> ins = new LinkedList<Integer>();
        for(int i=0; i<arr.length; i++){
            if(arr[i]!=sortedArr[i]){
                count++;
                ins.add(i);
            }
        }

        if(count == 2){
            System.out.println("yes");
            System.out.println("swap " + Integer.valueOf(ins.get(0)+1) + " " + Integer.valueOf(ins.get(1)+1));
            return;
        }

        ins = ins.stream().sorted().collect(Collectors.toList());
        int a = ins.get(0);
        int b = ins.get(ins.size()-1);

        boolean sortable = true;
        for(int i=a; i<b; i++){
            if(arr[i+1]>arr[i]){
                sortable = false;
                break;
            }
        }

        if(sortable){
            System.out.println("yes");
            System.out.println("reverse " + Integer.valueOf(a+1) + " " + Integer.valueOf(b+1));
        }
        else{
            System.out.println("no");
        }

    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        int n = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        int[] arr = new int[n];

        String[] arrItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < n; i++) {
            int arrItem = Integer.parseInt(arrItems[i]);
            arr[i] = arrItem;
        }

        almostSorted(arr);

        scanner.close();
    }
}

Solution in python3

Approach 1.

n=int(input())
l=list(map(int,input().split()))
sl=sorted(l)

diffcount = 0
diff1 = -1
diff2 = -1

for i in range(len(l)):
    if sl[i] != l[i]:
        diffcount += 1
        if diff1 == -1:
            diff1 = i
        elif diffcount > 1:
            diff2 = i
        lastdiff = i

if diffcount == 2:
    l[diff1], l[diff2] = l[diff2], l[diff1]
    if l == sl:
        print("yes")
        print("swap {} {}".format(diff1 + 1, diff2 + 1))
    else:
        print("no")
elif diffcount > 2:
    l = l[:diff1] + l[diff1:diff2 + 1][::-1] + l[diff2 + 1:]
    if l == sl:
        print("yes")
        print("reverse {} {}".format(diff1 + 1, diff2 + 1))
    else:
        print("no")

elif l == sl:
    print("yes")




































Approach 2.

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the almostSorted function below.
def almostSorted(arr):
    sArr = sorted(arr)
    misplaced = []
    for i in range(len(arr)):
        if sArr[i] != arr[i]:
            misplaced.append(i)
    if(len(misplaced)==0):
        print('yes')
    elif len(misplaced)==2:
        print('yes')
        print('swap',misplaced[0]+1, misplaced[1]+1)
    else:
        if sArr[misplaced[0]:misplaced[len(misplaced)-1]+1] == list(reversed(arr[misplaced[0]:misplaced[len(misplaced)-1]+1])):
            print('yes')
            print('reverse', misplaced[0]+1,misplaced[len(misplaced)-1]+1)
        else:
            print('no')
            
if __name__ == '__main__':
    n = int(input())

    arr = list(map(int, input().rstrip().split()))

    almostSorted(arr)

Approach 3.

#!/bin/python3

import math
import os
import random
import re
import sys
def swapped(arr, i, j):
    arr=arr[:]
    arr[i], arr[j]=arr[j], arr[i]
    return arr

def reverse(arr, i, j):
    aa=arr[:i]+list(reversed(arr[i:j+1]))
    if j!=len(arr)-1 :
        aa+=arr[j+1:] 
    return aa

# Complete the almostSorted function below.
def almostSorted(arr):
    sar=sorted(arr)
    i, j = 0, len(arr)-1
    while arr[i]<=arr[i+1]:i+=1
    while arr[j-1]<=arr[j]:j-=1
    if j<i:
        print ("yes")
    elif swapped(arr, i, j)==sar:
        print ("""yes
swap %d %d
                """ % (i+1, j+1))
    elif reverse(arr, i, j)==sar:
        print ("""yes
reverse %d %d
                """ % (i+1, j+1))
    else:
        print("no")

if __name__ == '__main__':
    n = int(input())

    arr = list(map(int, input().rstrip().split()))

    almostSorted(arr)

Solution in cpp

Approach 1.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
	/* Enter your code here. Read input from STDIN. Print output to STDOUT */

	int n;
	cin >> n;

	vector<int> v(n + 1);
	for (int z = 1; z < n + 1; z++) {
		cin >> v[z];
	}

	int i = 0, s = 0;
	for (i = 1; i <= n - 1; i++) {
		if (v[i] > v[i + 1]) {
			s = i;
			break;
		}
	}

	int j, e;
	for (j = i + 1; j <= n; j++) {
		if (v[s] < v[j]) {
			j -= 1;
			break;
		}
	}
	e = j;
	if (j > n) {
		e -= 1;
	}

	int k;
	for (k = e + 1; k < n - 1; k++) {
		if (v[k] > v[k + 1]) {
			cout << "no" << endl;
			return 0;
		}
	}

	if (s - 1 >= 0 && v[s - 1] > v[e] ) {
		cout << "no" << endl;
		return 0;
	}
	else if (e - s == 1 && v[s] > v[e]) {
		cout << "yes" << endl;
		cout << "swap" << " " << s << " " << e << endl;
	}
	else if (v[e - 1] > v[e]) {
		cout << "yes" << endl;
		for (k = e - 1; k >= s + 1; k--) {
			if (v[k - 1] < v[k]) {
				cout << "swap" << " " << s << " " << e << endl;
				return 0;
			}
		}
		cout << "reverse" << " " << s << " " << e << endl;
	}
	else {
		cout << "no" << endl;
		return 0;
	}

	return 0;
}

Approach 2.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

bool checksorted(vector <long> a){
    long last = -1;
    for(int i=0;i<a.size();i++){
        //cout << i<<"/"<<a.size()  <<" : " << a[i]<<endl;
        if(a[i] < last){
            return false;
        }
        last = a[i];
    }
    return true;
}

int main() {
    int n,last(-1),l(-1),r(0);
    vector <int> falls;
    long temp;
    cin>>n;
    vector <long> a(n);
    //bool sorted = true;
    for(int i=0;i<n;i++){
        cin>>a[i];
        if(a[i]<last && l==-1){
            l = i-1;
        }
        if(a[i]<last && l!=-1 && i>r ){
            r = i;
        }
        last = a[i];
    }
    if(l==-1){
        cout << "yes"<<endl;
        return 0;
    }
    vector <long> a2(a);
    a2[l] = a[r];
    a2[r] = a[l];
    if(checksorted(a2)){
        cout << "yes"<<endl<<"swap "<<l+1<<" "<<r+1<<endl;
        return 0;
    }
    for(int i=0;i< (r-l) ;i++){
        a2[l+i]=a[r-i];
    }
    if(checksorted(a2)){
        cout << "yes"<<endl<<"reverse "<<l+1<<" "<<r+1<<endl;
        return 0;
    }
    cout << "no"<<endl;
    return 0;
}

Approach 3.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    long n,a[100000],flag[100000],i,j=0,min;
    cin>>n;
    for(i=0;i<n;i++){
        cin>>a[i];
        if(i==0)
            min=a[0];
        else{
            if(min>=a[i]){
                flag[j]=i;
                j++;
            }
            min=a[i];
        }
    }
    //cout<<"j="<<j<<endl;
    if(j>2){
       long first=flag[0],count=1;
    for(i=1;i<j;i++){
        //cout<<flag[i]<<" ";
        if(flag[i]==first+1){
            first=flag[i];
            count++;
        }
        else{
            cout<<"no";
            return 0;
        }
    }
     cout<<"yes\n"<<"reverse "<<flag[0]<<" "<<flag[j-1]+1;  
    }
    else if(j==1){
        if(n>2){
            j=flag[0];
            if(a[j]>a[j-2])
                cout<<"yes\n"<<"swap "<<j<<" "<<j+1;
            else
            cout<<"no";
        }
        else
         cout<<"yes\n"<<"swap "<<1<<" "<<2;    
    }
    else{
      cout<<"yes\n"<<"swap "<<flag[0]<<" "<<flag[1]+1;  
    }
    return 0;
}

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe