Clean C++ using map and hashmap O(N*logN) time and O(N) space


  • 0
        string frequencySort(string s) {
          // create char frequency O(N)
          unordered_map<char,int> freq; for (char c:s) freq[c]++;
          // create sorted char frequency O(N*logN)
          map<int, unordered_set<char>> sortFreq; for (auto& p:freq) sortFreq[p.second].insert(p.first);
          // create string by char ascending frequency O(N)
          string res;
          for (auto it = sortFreq.rbegin(); it != sortFreq.rend(); ++it) {
            for (char c:it->second) res += string(it->first, c);  
          }
          return res;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.