-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday-22-sort_chars_by_frequency.cpp
52 lines (43 loc) · 1.41 KB
/
day-22-sort_chars_by_frequency.cpp
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Problem link: https://leetcode.com/problems/sort-characters-by-frequency/
#include <iostream>
#include <vector>
using namespace std;
// Time complexity => O(|s| * log|s|)
// Space complexity => O(|s\)
unordered_map<char, int> getCharCounts(string& s) {
unordered_map<char, int> charCounts;
for (char ch : s) {
charCounts[ch]++;
}
return charCounts;
}
priority_queue<pair<int, char>> getMaxHeap(string& s, unordered_map<char, int>& charCounts) {
priority_queue<pair<int, char>> maxHeap;
unordered_set<char> alreadyInsertedInHeap;
for (char ch : s) {
if (alreadyInsertedInHeap.find(ch) != alreadyInsertedInHeap.end()) continue;
pair<int, char> charInfo(charCounts[ch], ch);
maxHeap.push(charInfo);
alreadyInsertedInHeap.insert(ch);
}
return maxHeap;
}
string getFreqSortedStr(priority_queue<pair<int, char>>& maxHeap) {
string freqSortedStr = "";
while (!maxHeap.empty()) {
pair<int, char> topPair = maxHeap.top();
for (int i = 0; i < topPair.first; i++) {
freqSortedStr += topPair.second;
}
maxHeap.pop();
}
return freqSortedStr;
}
string frequencySort(string s) {
unordered_map<char, int> charCounts = getCharCounts(s);
priority_queue<pair<int, char>> maxHeap = getMaxHeap(s, charCounts);
string freqSortedStr = getFreqSortedStr(maxHeap);
return freqSortedStr;
}
int main() {
}