Skip to main content

Command Palette

Search for a command to run...

Strings - Sorting Characters By Frequency

Published
1 min read
Strings - Sorting Characters By Frequency
N

I am Nirbhay Singh , I am starting this blog to document my coding journey of becoming a software developer and to get my first $ 100k offer .

Sorting Characters By Frequency

  1. https://www.codingninjas.com/studio/problems/sorting-characters-by-frequency_1263699?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf&leftPanelTabValue=PROBLEM

  2. https://leetcode.com/problems/sort-characters-by-frequency/

Intiution:

  1. By looking at the contraints, it was clear the complexity has to be nlogn.

  2. Since they asked us to rearrange them in decreasing order that means higher frequency gets higher priority.

  3. Thus we can use max priority queue to solve our problem.

Code:

// TIME COMPLEXITY : O(NLOGN)
// SPACE COMPLEXITY : O(u)+O(u) , u is number of unique characters,
//                    Since the maximum unique characters is 26+26+10
//                    We can say the space is constant

string sortByFrequency(int n, string& s)
{
    // Write Your Code here

    // To store the frequency of unique characters
    unordered_map<char,int> m;

    for(int i=0;i<n;i++){
        if(m.count(s[i])>0){
            m[s[i]]++;
            continue;
        }

        m[s[i]] = 1;
    }


    // To store the characters in decreasing order of frequency
    priority_queue<pair<int,char>> pq;

    for(auto it: m){
        pq.push({it.second, it.first});
    }

    // storing the result from priority queue
    string ans = "";

    while(!pq.empty()){
        int freq = pq.top().first;
        char ch = pq.top().second;
        pq.pop();

        for(int i=0;i<freq;i++){
            ans+=ch;
        }
    }

    return ans;
}

DSA prep

Part 14 of 22

This series is specifically to document and share my learning of Data Structure and Algorithms and building the programmers intuition to solve a problem through coding and getting my first job as SDE.

Up next

Strings - Valid Anagram

Valid Anagram Problem Link: https://leetcode.com/problems/valid-anagram/description/ My approach: I used the concept of hashing. You can use hashmap or in this case just a simple array of size 26. Iterate through 's' string and update hash array b...

More from this blog

Daily Code by Nirbhay

74 posts

Hey, this is Nirbhay. I started this blog to document my journey of learning to code and get my first $100k offer. I'll be sharing the things related to DSA, backend development, devops and many more.