[Hacker Rank] Almost Sorted

Almost Sorted

  • Time : O(nlogn)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

void almostSorted(vector<int> A) {
int n = A.size(), l = 0, r = n - 1;
auto S = A;
sort(begin(S), end(S));
while(l < n and A[l] == S[l]) l++;
if(l == n) {
cout<<"yes"<<endl;
return;
}
while(r >= 0 and A[r] == S[r]) r--;
int unmatch = 0;
for(int i = l; i <= r; i++) {
if(A[i] != S[i]) unmatch++;
}
if(unmatch == 2) {
cout<<"yes"<<endl;
cout<<"swap "<<l + 1<<' '<<r + 1<<endl;
return;
}

for(int i = l, j = r; i <= r; i++,j--) {
if(A[j] != S[i]) {
cout<<"no"<<endl;
return;
}
}
cout<<"yes"<<endl;
cout<<"reverse "<<l + 1<<' '<<r + 1<<endl;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/15/PS/HackerRank/almost-sorted/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.