Posts

Showing posts from 2020

Kth most frequent Character in a given String

  Given a string   str   and an integer  K , the task is to find the K-th most frequent character in the string. If there are multiple characters that can account as K-th most frequent character then, print any one of them. Examples: Input:  str = “GeeksforGeeks”, K = 3 Output:  f Explanation: K = 3, here ‘e’ appears 4 times & ‘g’, ‘k’, ‘s’ appears 2 times & ‘o’, ‘f’, ‘r’ appears 1 time. Any output from ‘o’ (or) ‘f’ (or) ‘r’ will be correct. Input:  str = “trichotillomania”, K = 2 Output:  l The idea is to Use the Characters as key in  Hashmap  and store their  occurrences in the string . Sort the Hashmap  and find the K-th character. Below is the implementation of the above approach. // C++ program to find kth most frequent // character in a string #include <bits/stdc++.h> using namespace std;     // Used for sorting by frequency. bool sortByVal( const pair< char , int >& a,                 const pair< char , int >& b) {      return a.second >