Print characters and their frequencies in order of occurrence
Given string str containing only lowercase characters. The problem is to print the characters along with their frequency in the order of their occurrence and in the given format explained in the examples below.
Examples:
Input : str = "geeksforgeeks"
Output : g2 e4 k2 s2 f1 o1 r1
Input : str = "elephant"
Output : e2 l1 p1 h1 a1 n1 t1
Source: SAP Interview Experience | Set 26
Approach: Create a count array to store the frequency of each character in the given string str. Traverse the string str again and check whether the frequency of that character is 0 or not. If not 0, then print the character along with its frequency and update its frequency to 0 in the hash table. This is done so that the same character is not printed again.
C++
#include <bits/stdc++.h>
using namespace std;
#define SIZE 26
void printCharWithFreq(string str)
{
int n = str.size();
int freq[SIZE];
memset (freq, 0, sizeof (freq));
for ( int i = 0; i < n; i++)
freq[str[i] - 'a' ]++;
for ( int i = 0; i < n; i++) {
if (freq[str[i] - 'a' ] != 0) {
cout << str[i] << freq[str[i] - 'a' ] << " " ;
freq[str[i] - 'a' ] = 0;
}
}
}
int main()
{
string str = "geeksforgeeks" ;
printCharWithFreq(str);
return 0;
}
|
Java
public class Char_frequency {
static final int SIZE = 26 ;
static void printCharWithFreq(String str)
{
int n = str.length();
int [] freq = new int [SIZE];
for ( int i = 0 ; i < n; i++)
freq[str.charAt(i) - 'a' ]++;
for ( int i = 0 ; i < n; i++) {
if (freq[str.charAt(i) - 'a' ] != 0 ) {
System.out.print(str.charAt(i));
System.out.print(freq[str.charAt(i) - 'a' ] + " " );
freq[str.charAt(i) - 'a' ] = 0 ;
}
}
}
public static void main(String args[])
{
String str = "geeksforgeeks" ;
printCharWithFreq(str);
}
}
|
Python3
import numpy as np
def prCharWithFreq( str ) :
n = len ( str )
freq = np.zeros( 26 , dtype = np. int )
for i in range ( 0 , n) :
freq[ ord ( str [i]) - ord ( 'a' )] + = 1
for i in range ( 0 , n) :
if (freq[ ord ( str [i]) - ord ( 'a' )] ! = 0 ) :
print ( str [i], freq[ ord ( str [i]) - ord ( 'a' )],
end = " " )
freq[ ord ( str [i]) - ord ( 'a' )] = 0
if __name__ = = "__main__" :
str = "geeksforgeeks" ;
prCharWithFreq( str );
|
C#
using System;
class GFG {
static int SIZE = 26;
static void printCharWithFreq(String str)
{
int n = str.Length;
int [] freq = new int [SIZE];
for ( int i = 0; i < n; i++)
freq[str[i] - 'a' ]++;
for ( int i = 0; i < n; i++) {
if (freq[str[i] - 'a' ] != 0) {
Console.Write(str[i]);
Console.Write(freq[str[i] - 'a' ] + " " );
freq[str[i] - 'a' ] = 0;
}
}
}
public static void Main()
{
String str = "geeksforgeeks" ;
printCharWithFreq(str);
}
}
|
PHP
<?php
$SIZE = 26;
function printCharWithFreq( $str )
{
global $SIZE ;
$n = strlen ( $str );
$freq = array_fill (0, $SIZE , NULL);
for ( $i = 0; $i < $n ; $i ++)
$freq [ord( $str [ $i ]) - ord( 'a' )]++;
for ( $i = 0; $i < $n ; $i ++)
{
if ( $freq [ord( $str [ $i ]) - ord( 'a' )] != 0)
{
echo $str [ $i ] . $freq [ord( $str [ $i ]) -
ord( 'a' )] . " " ;
$freq [ord( $str [ $i ]) - ord( 'a' )] = 0;
}
}
}
$str = "geeksforgeeks" ;
printCharWithFreq( $str );
?>
|
Javascript
<script>
let SIZE = 26;
function printCharWithFreq(str)
{
let n = str.length;
let freq = new Array(SIZE);
for (let i = 0; i < freq.length; i++)
{
freq[i] = 0;
}
for (let i = 0; i < n; i++)
freq[str[i].charCodeAt(0) - 'a' .charCodeAt(0)]++;
for (let i = 0; i < n; i++) {
if (freq[str[i].charCodeAt(0) - 'a' .charCodeAt(0)] != 0) {
document.write(str[i]);
document.write(freq[str[i].charCodeAt(0) - 'a' .charCodeAt(0)] + " " );
freq[str[i].charCodeAt(0) - 'a' .charCodeAt(0)] = 0;
}
}
}
let str = "geeksforgeeks" ;
printCharWithFreq(str);
</script>
|
Output
g2 e4 k2 s2 f1 o1 r1
Time Complexity: O(n), where n is the number of characters in the string.
Auxiliary Space: O(1), as there are only lowercase letters.
Method #2: Using Unorderd_map & Hashing
We can also use unordered_map and hashing to solve the problem.
C++
#include <bits/stdc++.h>
using namespace std;
void prCharWithFreq(string s)
{
unordered_map< char , int > d;
for ( char i : s) {
d[i]++;
}
for ( char i : s) {
if (d[i] != 0) {
cout << i << d[i] << " " ;
d[i] = 0;
}
}
}
int main()
{
string s = "geeksforgeeks" ;
prCharWithFreq(s);
}
|
Java
import java.util.*;
class Gfg {
public static void prCharWithFreq(String s)
{
Map<Character, Integer> d
= new HashMap<Character, Integer>();
for ( int i = 0 ; i < s.length(); i++) {
if (d.containsKey(s.charAt(i))) {
d.put(s.charAt(i), d.get(s.charAt(i)) + 1 );
}
else {
d.put(s.charAt(i), 1 );
}
}
for ( int i = 0 ; i < s.length(); i++) {
if (d.get(s.charAt(i)) != 0 ) {
System.out.print(s.charAt(i));
System.out.print(d.get(s.charAt(i)) + " " );
d.put(s.charAt(i), 0 );
}
}
}
public static void main(String[] args)
{
String S = "geeksforgeeks" ;
prCharWithFreq(S);
}
}
|
Python3
def prCharWithFreq( str ):
d = {}
for i in str :
if i in d:
d[i] + = 1
else :
d[i] = 1
for i in str :
if d[i] ! = 0 :
print ( "{}{}" . format (i,d[i]), end = " " )
d[i] = 0
if __name__ = = "__main__" :
str = "geeksforgeeks" ;
prCharWithFreq( str );
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
class GFG {
public static void prCharWithFreq( string s)
{
Dictionary< char , int > d
= new Dictionary< char , int >();
foreach ( char i in s)
{
if (d.ContainsKey(i)) {
d[i]++;
}
else {
d[i] = 1;
}
}
foreach ( char i in s)
{
if (d[i] != 0) {
Console.Write(i + d[i].ToString() + " " );
d[i] = 0;
}
}
}
public static void Main( string [] args)
{
string s = "geeksforgeeks" ;
prCharWithFreq(s);
}
}
|
Javascript
<script>
function prCharWithFreq(s)
{
var d = new Map();
s.split( '' ).forEach(element => {
if (d.has(element))
{
d.set(element, d.get(element)+1);
}
else
d.set(element, 1);
});
s.split( '' ).forEach(element => {
if (d.has(element) && d.get(element)!=0)
{
document.write( element + d.get(element) + " " );
d.set(element, 0);
}
});
}
var s= "geeksforgeeks" ;
prCharWithFreq(s);
</script>
|
Output
g2 e4 k2 s2 f1 o1 r1
Time Complexity: O(n), where n is the number of characters in the string.
Auxiliary Space: O(n),
Method #3: Using Object-Oriented programming:
We can solve this problem without using a HashMap too. But, we then have to create our own class whose objects will have 2 properties – character and its occurrence.
- We create a class in this case called as CharOccur and initialize 2 variables character and occurrence in its constructor.
- In the main of our original class we will just create a list that can store these objects.
Logic –
- Loop through the string.
- Check if string’s current character is already present in some object. If present then increment its occurrence else set its occurrence to 1.
C++
#include <bits/stdc++.h>
using namespace std;
class CharOccur {
public :
char character;
int occurrence = 0;
CharOccur( char character, int occurrence)
{
this ->character = character;
this ->occurrence = occurrence;
}
};
void frequency(string s)
{
if (s.size() == 0) {
cout << "Empty string" << endl;
return ;
}
vector<CharOccur> occurrences;
for ( int i = 0; i < s.size(); i++) {
char c = s[i];
int flag = 0;
for ( auto & o : occurrences) {
if (o.character == c) {
o.occurrence += 1;
flag = 1;
}
}
if (flag == 0) {
CharOccur grp(c, 1);
occurrences.push_back(grp);
}
}
for ( auto o : occurrences) {
cout << o.character << " " << o.occurrence << endl;
}
}
int main()
{
string s1 = "GFG" ;
cout << "For " << s1 << endl;
frequency(s1);
string s2 = "aaabccccffgfghc" ;
cout << "For " << s2 << endl;
frequency(s2);
}
|
Java
import java.io.*;
import java.util.ArrayList;
class GFG {
public static void main(String[] args)
{
String s1 = "GFG" ;
System.out.println( "For " + s1);
frequency(s1);
String s2 = "aaabccccffgfghc" ;
System.out.println( "For " + s2);
frequency(s2);
}
private static void frequency(String s)
{
if (s.length() == 0 ) {
System.out.println( "Empty string" );
return ;
}
ArrayList<CharOccur> occurrences
= new ArrayList<CharOccur>();
for ( int i = 0 ; i < s.length(); i++) {
char c = s.charAt(i);
int flag = 0 ;
for (CharOccur o : occurrences) {
if (o.character == c) {
o.occurrence += 1 ;
flag = 1 ;
}
}
if (flag == 0 ) {
CharOccur grp = new CharOccur(c, 1 );
occurrences.add(grp);
}
}
for (CharOccur o : occurrences) {
System.out.println(o.character + " "
+ o.occurrence);
}
}
}
class CharOccur {
char character;
int occurrence = 0 ;
CharOccur( char character, int occurrence)
{
this .character = character;
this .occurrence = occurrence;
}
}
|
Python3
class CharOccur:
def __init__( self , character, occurrence):
self .character = character
self .occurrence = occurrence
def frequency(s: str ):
if not s:
print ( "Empty string" )
return
occurrences = []
for c in s:
found = False
for occur in occurrences:
if occur.character = = c:
occur.occurrence + = 1
found = True
break
if not found:
occurrences.append(CharOccur(c, 1 ))
for occur in occurrences:
print (occur.character, occur.occurrence)
s1 = "GFG"
print ( "For " + s1)
frequency(s1)
s2 = "aaabccccffgfghc"
print ( "For " + s2)
frequency(s2)
|
C#
using System;
using System.Collections.Generic;
class CharOccur {
public char character;
public int occurrence = 0;
public CharOccur( char character, int occurrence)
{
this .character = character;
this .occurrence = occurrence;
}
}
class Program {
static void frequency( string s)
{
if ( string .IsNullOrEmpty(s)) {
Console.WriteLine( "Empty string" );
return ;
}
List<CharOccur> occurrences = new List<CharOccur>();
for ( int i = 0; i < s.Length; i++) {
char c = s[i];
bool found = false ;
for ( int j = 0; j < occurrences.Count; j++) {
if (occurrences[j].character == c) {
occurrences[j].occurrence++;
found = true ;
break ;
}
}
if (!found) {
occurrences.Add( new CharOccur(c, 1));
}
}
for ( int i = 0; i < occurrences.Count; i++) {
Console.WriteLine(occurrences[i].character + " "
+ occurrences[i].occurrence);
}
}
static void Main()
{
string s1 = "GFG" ;
Console.WriteLine( "For " + s1);
frequency(s1);
string s2 = "aaabccccffgfghc" ;
Console.WriteLine( "For " + s2);
frequency(s2);
}
}
|
Javascript
class CharOccur{
constructor( character, occurrence)
{
this .character = character;
this .occurrence = occurrence;
}
}
function frequency(s)
{
if (s.length== 0) {
document.write( "Empty string" );
return ;
}
let occurrences=[];
for (let i = 0; i < s.length; i++) {
let c = s[i];
let flag = 0;
for (let i=0;i< occurrences.length;i++) {
if (occurrences[i].character == c) {
occurrences[i].occurrence += 1;
flag = 1;
}
}
if (flag == 0) {
let grp= new CharOccur(c, 1);
occurrences.push(grp);
}
}
for (let i=0;i< occurrences.length;i++) {
let o = occurrences[i];
console.log(o.character + " " + o.occurrence);
}
}
let s1 = "GFG" ;
console.log( "For " + s1);
frequency(s1);
let s2 = "aaabccccffgfghc" ;
console.log( "For " + s2);
frequency(s2);
|
Output
For GFG
G 2
F 1
For aaabccccffgfghc
a 3
b 1
c 5
f 3
g 2
h 1
Complexity analysis:
- Time Complexity: O(n), where n is the number of characters in the string.
- Auxiliary Space: O(n)
Method #4: Using built-in Python functions:
We can solve this problem quickly using the python Counter() method. The approach is very simple.
1) First create a dictionary using the Counter method having strings as keys and their frequencies as values.
2)Traverse in this dictionary print keys along with their values
C++
#include <bits/stdc++.h>
using namespace std;
void prCharWithFreq(string str)
{
map< char , int > mp;
for ( int i = 0; i < str.length(); i++)
mp[str[i]]++;
int count[256] = { 0 };
for ( int i = 0; i < str.length(); i++) {
if (count[str[i]] == 0) {
cout << str[i] << mp[str[i]] << " " ;
count[str[i]]++;
}
}
cout << endl;
}
int main()
{
string str = "geeksforgeeks" ;
prCharWithFreq(str);
return 0;
}
|
Java
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void prCharWithFreq(String string)
{
Map<Character, Integer> d = new HashMap<>();
for ( int i = 0 ; i < string.length(); i++) {
char c = string.charAt(i);
if (d.containsKey(c)) {
d.put(c, d.get(c) + 1 );
}
else {
d.put(c, 1 );
}
}
for ( int i = 0 ; i < string.length(); i++) {
char c = string.charAt(i);
if (d.containsKey(c)) {
System.out.print(
c + Integer.toString(d.get(c)) + " " );
d.remove(c);
}
}
}
public static void main(String[] args)
{
String string = "geeksforgeeks" ;
prCharWithFreq(string);
}
}
|
Python3
from collections import Counter
def prCharWithFreq(string):
d = Counter(string)
for i in d:
print (i + str (d[i]), end = " " )
string = "geeksforgeeks"
prCharWithFreq(string)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG
{
public static void PrCharWithFreq( string str)
{
Dictionary< char , int > freqDict = new Dictionary< char , int >();
foreach ( char c in str)
{
if (freqDict.ContainsKey(c))
{
freqDict++;
}
else
{
freqDict = 1;
}
}
foreach ( char c in str)
{
if (freqDict.ContainsKey(c))
{
Console.Write(c + freqDict.ToString() + " " );
freqDict.Remove(c);
}
}
}
public static void Main()
{
string str = "geeksforgeeks" ;
PrCharWithFreq(str);
}
}
|
Javascript
function prCharWithFreq(str) {
let mp = {};
for (let i = 0; i < str.length; i++) {
mp[str[i]] = mp[str[i]] ? mp[str[i]] + 1 : 1;
}
let count = {};
for (let i = 0; i < str.length; i++) {
if (!count[str[i]]) {
console.log(str[i] + mp[str[i]] + " " );
count[str[i]] = true ;
}
}
console.log( "\n" );
}
let str = "geeksforgeeks" ;
prCharWithFreq(str);
|
Output
g2 e4 k2 s2 f1 o1 r1
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
08 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...