HackerRank Matrix Layer Rotation Solution

Hello Programmers, In this post, you will know how to solve the HackerRank Matrix Layer Rotation Solution. This problem is a part of the HackerRank Algorithms Series.

HackerRank Matrix Layer Rotation Solution
HackerRank Matrix Layer Rotation Solution

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

HackerRank Matrix Layer Rotation Solution

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 Matrix Layer Rotation Solution

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

Matrix Layer Rotation 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;
}

Matrix Layer Rotation Solution in Java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Solution5 {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int[] d = new int[n];
		int[] sorted = new int[n];
		for(int i = 0; i < n; i++) {
			d[i] = in.nextInt();
			sorted[i] = d[i];
		}
		Arrays.sort(sorted);
		ArrayList<Integer> diff = new ArrayList<Integer>();
		for(int i = 0; i < n; i++) {
			if(d[i] != sorted[i]) {
				diff.add(i);
				if(diff.size() == 3) {
					break;
				}
			}
		}
		if(diff.size() == 2) {
			System.out.println("yes");
			System.out.println("swap " + (diff.get(0) + 1) + " " + (diff.get(1) + 1));
		} else {
			int first = -1;
			int last = Integer.MAX_VALUE;
			for(int i = 0; i < n; i++) {
				if(d[i] != sorted[i]) {
					if(first == -1) {
						first = i;
					}
					last = i;
				}
			}
			if(first == -1) {
				System.out.println("no");
			} else {
				boolean works = true;
				for(int i = 0; i < last - first; i++) {
					if(d[first + i] != sorted[last - i]) {
						works = false;
						break;
					}
				}
				if(works) {
					System.out.println("yes");
					System.out.println("reverse " + (first + 1) + " " + (last + 1));
				} else {
					System.out.println("no");
				}
			}
		}
	}
}
Ezoicreport this ad

Matrix Layer Rotation 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)
    }
}
 

Ezoicreport this adAlmost Sorted Solution in Pascal

uses  math;
var f:text; n,i,l,r:longint; t:boolean;
    a,id:array[0..100000]of longint;
    
procedure sort(l,r:longint);
var i,j,x,t:longint;
begin
  if l>=r then exit;
  i:=l; j:=r; x:=a[id[(l+r)div 2]];
  repeat
    while a[id[i]]<x do inc(i);
    while a[id[j]]>x do dec(j);
    if i<=j then
    begin
      t:=id[i]; id[i]:=id[j]; id[j]:=t;
      inc(i); dec(j)
    end
  until i>j;
  sort(l,j); sort(i,r)
end;
    
procedure swap(var a,b:longint);
var t:longint;
begin t:=a; a:=b; b:=t end;
procedure reverse(l,r:longint);
var i:longint;
    b:array[0..100000]of longint;
begin
  for i:=1 to l-1 do b[i]:=a[i];
  for i:=r downto l do
    b[r-i+l]:=a[i];
  for i:=r+1 to n do b[i]:=a[i];
  a:=b
end;
function sorted:boolean;
var i:longint;
begin
  sorted:=true;
  for i:=2 to n do
    if a[i]<a[i-1] then
      exit(false)
end;
    
begin
  assign(f,''); reset(f); readln(f,n);
  t:=true;
  for i:=1 to n do
  begin
    read(f,a[i]);
    if i>1 then
      if a[i]<a[i-1] then
        t:=false;
    id[i]:=i
  end;
  close(f);
  assign(f,''); rewrite(f);
  l:=100001; r:=0;
  if t then write(f,'yes')
  else
  begin
    sort(1,n);
    for i:=1 to n do
      if id[i]<>i then
      begin
        l:=min(l,id[i]);
        r:=max(r,id[i])
      end;
    swap(a[l],a[r]);
    if sorted then
    begin
      writeln(f,'yes');
      write(f,'swap ',l,' ',r)
    end
    else
    begin
      swap(a[l],a[r]); reverse(l,r);
      if sorted then
      begin
        writeln(f,'yes');
        write(f,'reverse ',l,' ',r)
      end
      else write(f,'no')
    end
  end;
  close(f)
end.

Disclaimer: This problem (Matrix Layer Rotation) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: HackerRank Almost Sorted Solution

Sharing Is Caring

Leave a Comment

Ezoicreport this ad