Sort Characters By Frequency in C++

C++Server Side ProgrammingProgramming

Suppose we have a string, we have to sort the characters based on the frequency. So if the string is like “abbbacbcc”, then the output will be “bbbbcccaa”

To solve this, we will follow these steps −

  • create an array of pairs called v, create one map m
  • for all characters in string,
    • increase value of m[character] by 1
  • i := first element of map
  • while map has elements
    • insert (i.second, i.first) into v
    • and increase i to point to the next element
  • sort the vector v
  • ans := an empty string
  • for i := 0 to size of v
    • t := first element of v[i]
    • while t is not 0
      • ans := ans + second part of v[i]
      • decrease t by 1
  • return ans


Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   static bool cmp(pair <int, char> a, pair <int, char> b){
      return a.first < b.first;
   string frequencySort(string s) {
      vector < pair <int, char> > v;
      map <char, int> m;
      for(int i = 0; i < s.size(); i++){
      map <char, int> :: iterator i = m.begin();
      while(i != m.end()){
         v.push_back({i->second, i->first});
      sort(v.rbegin(), v.rend(), cmp);
      string ans = "";
      for(int i = 0; i < v.size(); i++){
         int t = v[i].first;
         while(t--)ans += v[i].second;
      return ans;
   Solution ob;
   cout << ob.frequencySort("abbbacbcc");




Published on 27-Feb-2020 14:22:59