[Hacker Rank] Reverse Shuffle Merge

Reverse Shuffle Merge

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
string reverseShuffleMerge(string s) {
unordered_map<char, int> freq;
unordered_map<char, int> req;
reverse(begin(s), end(s));
for(auto& ch : s) freq[ch]++;
for(auto& [k, v] : freq) req[k] = v / 2;
string res = "";

for(int i = 0; i < s.length(); i++) {
if(req[s[i]]) {
while(!res.empty() and res.back() > s[i] and freq[res.back()] >= req[res.back()] + 1) {
req[res.back()]++;
res.pop_back();
}
res.push_back(s[i]);
req[s[i]]--;
}
freq[s[i]]--;
}
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/10/PS/HackerRank/reverse-shuffle-merge/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.