[Hacker Rank] Absolute Permutation

Absolute Permutation

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
vector<int> absolutePermutation(int n, int k) {
vector<int> res;
unordered_set<int> us;
for(int i = 1; i <= n; i++) {
if(i-k > 0 and !us.count(i-k)) res.push_back(i - k);
else res.push_back(i + k);
if(us.count(res.back())) return {-1};
if(res.back() > n) return {-1};
us.insert(res.back());
}
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/13/PS/HackerRank/absolute-permutation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.