# HackerRank Matrix Layer Rotation Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Matrix Layer Rotation 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.

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

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

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

### Almost 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
t:=true;
for i:=1 to n do
begin
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 (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.