Frequency of lexicographically Kth smallest character in the a string
Last Updated :
29 Jan, 2022
Given a string S of length N and an integer K, the task is to find the frequency of the lexicographically Kth smallest character present in the given string.
Examples:
Input: S = “geeksforgeeks”, K = 3
Output: 4
Explanation: The lexicographically 3rd smallest character in S is ‘e’. Frequency of ‘e’ in S = 4.
Input: S = “abcdabcd”, K = 4
Output: 2
Explanation: The lexicographically 4th smallest lexicographical character in S is ‘b’. Frequency of ‘b’ in S = 2.
Approach: The idea is to sort the string in ascending order of their ASCII values. Now, find the (K – 1)th character in the sorted string and find its frequency. Follow the steps below to solve the problem:
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
void KthCharacter(
string S, int N, int K)
{
char strarray[N + 1];
strcpy (strarray, S.c_str());
sort(strarray, strarray + N);
char ch = strarray[K - 1];
int count = 0;
for ( auto c : strarray)
{
if (c == ch)
count++;
}
cout << count;
}
int main()
{
string S = "geeksforgeeks" ;
int N = S.length();
int K = 3;
KthCharacter(S, N, K);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static void KthCharacter(
String S, int N, int K)
{
char strarray[] = S.toCharArray();
Arrays.sort(strarray);
char ch = strarray[K - 1 ];
int count = 0 ;
for ( char c : strarray) {
if (c == ch)
count++;
}
System.out.println(count);
}
public static void main(String[] args)
{
String S = "geeksforgeeks" ;
int N = S.length();
int K = 3 ;
KthCharacter(S, N, K);
}
}
|
Python3
def KthCharacter(S, N, K):
strarray = [char for char in S];
strarray.sort();
ch = strarray[K - 1 ];
count = 0 ;
for c in strarray:
if (c = = ch):
count + = 1 ;
print (count);
if __name__ = = '__main__' :
S = "geeksforgeeks" ;
N = len (S);
K = 3 ;
KthCharacter(S, N, K);
|
C#
using System;
class GFG
{
public static void KthCharacter(
string S, int N, int K)
{
char [] strarray = S.ToCharArray();
Array.Sort(strarray);
char ch = strarray[K - 1];
int count = 0;
foreach ( char c in strarray)
{
if (c == ch)
count++;
}
Console.Write(count);
}
public static void Main()
{
string S = "geeksforgeeks" ;
int N = S.Length;
int K = 3;
KthCharacter(S, N, K);
}
}
|
Javascript
<script>
function KthCharacter(S, N, K)
{
var strarray = S.split( '' );
strarray.sort();
var ch = strarray[K - 1];
var count = 0;
strarray.forEach(c => {
if (c == ch)
count++;
});
document.write(count);
}
var S = "geeksforgeeks" ;
var N = S.length;
var K = 3;
KthCharacter(S, N, K);
</script>
|
Time Complexity: O(N*log N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...