[Hacker Rank] Lily`s Homework

Lily’s Homework

  • 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
31
32
33
34
35
36
37
int forward(vector<int> A) {
int res = 0, n = A.size();
auto s = A;
sort(begin(s), end(s));
unordered_map<int, int> mp;
for(int i = 0; i < n; i++) mp[A[i]] = i;

for(int i = 0; i < n; i++) {
if(s[i] == A[i]) continue;
int idx = mp[s[i]];
mp[A[i]] = idx;
swap(A[i], A[idx]);
res++;
}
return res;
}

int backword(vector<int> A) {
int res = 0, n = A.size();
auto s = A;
sort(rbegin(s), rend(s));
unordered_map<int, int> mp;
for(int i = 0; i < n; i++) mp[A[i]] = i;

for(int i = 0; i < n; i++) {
if(s[i] == A[i]) continue;
int idx = mp[s[i]];
mp[A[i]] = idx;
swap(A[i], A[idx]);
res++;
}
return res;
}

int lilysHomework(vector<int> arr) {
return min(forward(arr), backword(arr));
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/10/PS/HackerRank/lilys-homework/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.