Find Character Frequencies in Order of Occurrence
Last Updated :
14 Nov, 2024
Given string s containing only lowercase characters, the task 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: s = "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
[Naive Approach] Using Nested Loops - O(n^2) Time and O(1) Space
Traverse through every character and count frequency of it using one more loop inside the main traversal loop. To ensure that we do not have repeated characters in output, check if the character is already seen. If already seen, then ignore the character.
C++
// C++ Code to find character frequencies in order of
// occurrence using Nested Loops
#include <iostream>
using namespace std;
// function to modify the string by appending
// character with its frequency in order of occurrence
string modifyString(string &s) {
string res = "";
int n = s.size();
// loop through the string
for (int i = 0; i < n; i++) {
// count the occurrence of s[i]
int count = 1;
// check if the character has been
// processed already
bool seen = false;
for (int j = 0; j < i; j++) {
if (s[j] == s[i]) {
seen = true;
break;
}
}
if (seen) continue;
// count frequency of s[i]
for (int j = i + 1; j < n; j++) {
if (s[j] == s[i]) {
count++;
}
}
// append character and its frequency
// to the result
res += s[i] + to_string(count) + " ";
}
return res;
}
int main() {
string s = "geeksforgeeks";
cout << modifyString(s);
return 0;
}
Java
// Java Code to find character frequencies in order of
// occurrence using Nested Loops
import java.util.*;
class GfG {
// function to modify the string by appending
// character with its frequency in order of occurrence
static String modifyString(String s) {
String res = "";
int n = s.length();
// loop through the string
for (int i = 0; i < n; i++) {
// count the occurrence of s[i]
int count = 1;
// check if the character has been
// processed already
boolean seen = false;
for (int j = 0; j < i; j++) {
if (s.charAt(j) == s.charAt(i)) {
seen = true;
break;
}
}
if (seen) continue;
// count frequency of s[i]
for (int j = i + 1; j < n; j++) {
if (s.charAt(j) == s.charAt(i)) {
count++;
}
}
// append character and its frequency
// to the result
res += s.charAt(i) + Integer.toString(count) + " ";
}
return res;
}
public static void main(String[] args) {
String s = "geeksforgeeks";
System.out.println(modifyString(s));
}
}
Python
# Python Code to find character frequencies in order of
# occurrence using Nested Loops
# function to modify the string by appending
# character with its frequency in order of occurrence
def modifyString(s):
res = ""
n = len(s)
# loop through the string
for i in range(n):
# count the occurrence of s[i]
count = 1
# check if the character has been
# processed already
seen = False
for j in range(i):
if s[j] == s[i]:
seen = True
break
if seen: continue;
# count frequency of s[i]
for j in range(i + 1, n):
if s[j] == s[i]:
count += 1
# append character and its frequency
# to the result
res += s[i] + str(count) + " "
return res
s = "geeksforgeeks"
print(modifyString(s))
C#
// C# Code to find character frequencies in order of
// occurrence using Nested Loops
using System;
class GfG {
// function to modify the string by appending
// character with its frequency in order of occurrence
static string modifyString(string s) {
string res = "";
int n = s.Length;
// loop through the string
for (int i = 0; i < n; i++) {
// count the occurrence of s[i]
int count = 1;
// check if the character has been
// processed already
bool seen = false;
for (int j = 0; j < i; j++) {
if (s[j] == s[i]) {
seen = true;
break;
}
}
if (seen) continue;
// count frequency of s[i]
for (int j = i + 1; j < n; j++) {
if (s[j] == s[i]) {
count++;
}
}
// append character and its frequency
// to the result
res += s[i] + count.ToString() + " ";
}
return res;
}
static void Main(string[] args) {
string s = "geeksforgeeks";
Console.WriteLine(modifyString(s));
}
}
JavaScript
// JavaScript Code to find character frequencies in order of
// occurrence using Nested Loops
// function to modify the string by appending
// character with its frequency in order of occurrence
function modifyString(s) {
let res = "";
let n = s.length;
// loop through the string
for (let i = 0; i < n; i++) {
// count the occurrence of s[i]
let count = 1;
// check if the character has been
// processed already
let seen = false;
for (let j = 0; j < i; j++) {
if (s[j] === s[i]) {
seen = true;
break;
}
}
if (seen) continue;
// count frequency of s[i]
for (let j = i + 1; j < n; j++) {
if (s[j] === s[i]) {
count++;
}
}
// append character and its frequency
// to the result
res += s[i] + count.toString() + " ";
}
return res;
}
let s = "geeksforgeeks";
console.log(modifyString(s));
Outputg2 e4 k2 s2 f1 o1 r1
[Expected Approach 1] Use Hash Map or Dictionary - O(n) Time and O(MAX_CHAR) Space
1) Store Frequencies of all characters in a map.
2) Traverse through the string, append the character and its frequency to the result and make frequency as 0 to avoid repetition.
Note the MAX_CHAR is alphabet size of input characters which is typically a constant. If we have only lower case characters, then MAX_CHAR is 26 only. If we consider all ASCII characters, then MAX_CHAR is 256.
C++
// C++ Code to find character frequencies in order of
// occurrence using Hash Map
#include <iostream>
#include<unordered_map>
using namespace std;
// function to return the characters and
// frequencies in the order of their occurrence
string modifyString(string &s) {
unordered_map<char, int> d;
string res = "";
// Store all characters and their frequencies
for (char i : s) {
d[i]++;
}
// Build the result string with characters
// and their frequencies
for (char i : s) {
if (d[i] != 0) {
// append character and frequency
res += i + to_string(d[i]) + " ";
// mark as processed
d[i] = 0;
}
}
return res;
}
int main() {
string s = "geeksforgeeks";
cout << modifyString(s);
return 0;
}
Java
// Java Code to find character frequencies in order of
// occurrence using Hash Map
import java.util.*;
class Gfg {
public static void modifyString(String s)
{
// Store all characters and
// their frequencies in dictionary
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);
}
}
// Print characters and their
// frequencies in same order
// of their appearance
for (int i = 0; i < s.length(); i++) {
// Print only if this
// character is not printed
// before
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);
}
}
}
// Driver code
public static void main(String[] args)
{
String S = "geeksforgeeks";
modifyString(S);
}
}
Python
# Python Code to find character frequencies in order of
# occurrence using Hash Map
def modifyString(str):
# Store all characters and their frequencies
# in dictionary
d = {}
for i in str:
if i in d:
d[i] += 1
else:
d[i] = 1
# Print characters and their frequencies in
# same order of their appearance
for i in str:
# Print only if this character is not printed
# before.
if d[i] != 0:
print("{}{}".format(i,d[i]), end =" ")
d[i] = 0
if __name__ == "__main__" :
str = "geeksforgeeks";
modifyString(str);
C#
// C# Code to find character frequencies in order of
// occurrence using Hash Map
using System;
using System.Collections;
using System.Collections.Generic;
class GFG {
public static void modifyString(string s)
{
// Store all characters and
// their frequencies in dictionary
Dictionary<char, int> d
= new Dictionary<char, int>();
foreach(char i in s)
{
if (d.ContainsKey(i)) {
d[i]++;
}
else {
d[i] = 1;
}
}
// Print characters and their
// frequencies in same order
// of their appearance
foreach(char i in s)
{
// Print only if this
// character is not printed
// before
if (d[i] != 0) {
Console.Write(i + d[i].ToString() + " ");
d[i] = 0;
}
}
}
// Driver Code
public static void Main(string[] args)
{
string s = "geeksforgeeks";
modifyString(s);
}
}
// This code is contributed by pratham76
JavaScript
// JavaScript Code to find character frequencies in order of
// occurrence using Hash Map
function modifyString(s) {
let d = {};
let res = "";
// Store all characters and their frequencies
for (let i of s) {
d[i] = (d[i] || 0) + 1;
}
// Build the result string with characters
// and their frequencies
for (let i of s) {
if (d[i] !== 0) {
// append character and frequency
res += i + d[i] + " ";
// mark as processed
d[i] = 0;
}
}
return res;
}
function main() {
let s = "geeksforgeeks";
console.log(modifyString(s));
}
main();
Outputg2 e4 k2 s2 f1 o1 r1
[Expected Approach 2] Use Frequency Array - O(n) Time and O(MAX_CHAR) Space
Create a frequency array to store frequency of each character. We are going to use characters as index in this array. The frequency of 'a' is going to be stored at index 0, 'b' at 1, and so on. To find the index of a character, we subtract character a's ASCII value from the ASCII value of the character.
Traverse the string 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 frequency array. This is done so that the same character is not printed again. This is the same approach as above, but instead of using library hash map, we use an array to ensure that we get the fast results.
C++
// C++ Code to find character frequencies in order of
// occurrence using Frequency Array
#include <iostream>
using namespace std;
const int MAX_CHAR=26;
// function to modify the string by appending
// character with its frequency in order of occurrence
string modifyString(string &s) {
// Store frequencies of all characters
int freq[MAX_CHAR] = {0};
for (char c : s)
freq[c - 'a']++;
string res = "";
for (char c : s) {
if (freq[c - 'a'] != 0) {
// append character and frequency
res += c + to_string(freq[c - 'a'])+" ";
// mark as processed
freq[c - 'a'] = 0;
}
}
return res;
}
int main() {
string s = "geeksforgeeks";
cout << modifyString(s);
return 0;
}
Java
// Java implementation to print the character and
// its frequency in order of its occurrence
public class Char_frequency {
static final int MAX_CHAR = 26;
// function to print the character and its
// frequency in order of its occurrence
static void printCharWithFreq(String str)
{
// size of the string 'str'
int n = str.length();
// 'freq[]' implemented as hash table
int[] freq = new int[MAX_CHAR];
// accumulate frequency of each character
// in 'str'
for (int i = 0; i < n; i++)
freq[str.charAt(i) - 'a']++;
// traverse 'str' from left to right
for (int i = 0; i < n; i++) {
// if frequency of character str.charAt(i)
// is not equal to 0
if (freq[str.charAt(i) - 'a'] != 0) {
// print the character along with its
// frequency
System.out.print(str.charAt(i));
System.out.print(freq[str.charAt(i) - 'a'] + " ");
// update frequency of str.charAt(i) to
// 0 so that the same character is not
// printed again
freq[str.charAt(i) - 'a'] = 0;
}
}
}
// Driver program to test above
public static void main(String args[])
{
String str = "geeksforgeeks";
printCharWithFreq(str);
}
}
Python
# C++ Code to find character frequencies in order of
# occurrence using Frequency Array
MAX_CHAR = 26
# function to modify the string by appending
# character with its frequency in order of occurrence
def modifyString(s):
# Store frequencies of all characters
freq = [0] * MAX_CHAR
for c in s:
freq[ord(c) - ord('a')] += 1
res = ""
for c in s:
if freq[ord(c) - ord('a')] != 0:
# append character and frequency
res += c + str(freq[ord(c) - ord('a')]) + " "
# mark as processed
freq[ord(c) - ord('a')] = 0
return res
s = "geeksforgeeks"
print(modifyString(s))
C#
// C++ Code to find character frequencies in order of
// occurrence using Frequency Array
using System;
class GFG {
static int MAX_CHAR = 26;
// function to print the character and its
// frequency in order of its occurrence
static void printCharWithFreq(String str)
{
// size of the string 'str'
int n = str.Length;
// 'freq[]' implemented as hash table
int[] freq = new int[MAX_CHAR];
// accumulate frequency of each character
// in 'str'
for (int i = 0; i < n; i++)
freq[str[i] - 'a']++;
// traverse 'str' from left to right
for (int i = 0; i < n; i++) {
// if frequency of character str.charAt(i)
// is not equal to 0
if (freq[str[i] - 'a'] != 0) {
// print the character along with its
// frequency
Console.Write(str[i]);
Console.Write(freq[str[i] - 'a'] + " ");
// update frequency of str.charAt(i) to
// 0 so that the same character is not
// printed again
freq[str[i] - 'a'] = 0;
}
}
}
public static void Main()
{
String str = "geeksforgeeks";
printCharWithFreq(str);
}
}
JavaScript
// C++ Code to find character frequencies in order of
// occurrence using Frequency Array
function modifyString(s) {
// Store frequencies of all characters
let freq = new Array(26).fill(0);
for (let c of s) {
freq[c.charCodeAt(0) - 'a'.charCodeAt(0)]++;
}
let res = "";
for (let c of s) {
if (freq[c.charCodeAt(0) - 'a'.charCodeAt(0)] !== 0) {
// append character and frequency
res += c + freq[c.charCodeAt(0) - 'a'.charCodeAt(0)] + " ";
// mark as processed
freq[c.charCodeAt(0) - 'a'.charCodeAt(0)] = 0;
}
}
return res;
}
let s = "geeksforgeeks";
console.log(modifyString(s));
Using Counter in Python
Python
from collections import Counter
def prCharWithFreq(s):
# Count the frequency of each character
freq = Counter(s)
res = ""
# Iterate over the string and append characters
# with their frequencies
for char in s:
if freq[char] != 0:
res += char + str(freq[char]) + " "
freq[char] = 0 # mark as processed
return res
# Driver code
s = "geeksforgeeks"
print(prCharWithFreq(s))
Similar Reads
Print characters having even frequencies in order of occurrence Given a string str containing only lowercase characters. The task is to print the characters having an even frequency in the order of their occurrence.Note: Repeated elements with even frequency are printed as many times they occur in order of their occurrences.Examples: Input: str = "geeksforgeeks"
5 min read
Print characters having odd frequencies in order of occurrence Given a string str containing only lowercase characters. The task is to print the characters having an odd frequency in the order of their occurrence.Note: Repeated elements with odd frequency are printed as many times they occur in order of their occurrences.Examples: Input: str = "geeksforgeeks" O
7 min read
Print characters having prime frequencies in order of occurrence Given a string str containing only lowercase characters. The task is to print the characters having prime frequency in the order of their occurrence. Note that repeated elements with prime frequencies are printed as many times as they occur in order of their occurrence. Examples: Input: str = "geeks
11 min read
Find given occurrences of Mth most frequent element of Array Given an array arr[], integer M and an array query[] containing Q queries, the task is to find the query[i]th occurrence of Mth most frequent element of the array. Examples: Input: arr[] = {1, 2, 20, 8, 8, 1, 2, 5, 8, 0, 6, 8, 2}, M = 1, query[] = {100, 4, 2}Output: -1, 12, 5Explanation: Here most f
9 min read
Queries for frequencies of characters in substrings Given a string s and Q number of queries. Each query Q consists of l and r and a character c. Find the frequency of character c in substring l to r. Examples: Input : s = geeksforgeeks 4 0 5 e 2 6 f 4 7 m 0 12 e Output : 2 1 0 4 Substring from 0 to 5 is geeksf. Here e occurs 2 times. Input : s = app
6 min read
Frequency of Characters in Alphabetical Order Given a string s, the task is to print the frequency of each of the characters of s in alphabetical order.Example: Input: s = "aabccccddd" Output: a2b1c4d3 Since it is already in alphabetical order, the frequency of the characters is returned for each character. Input: s = "geeksforgeeks" Output: e4
9 min read
Print characters and their frequencies in order of occurrence using a LinkedHashMap in Java Given a string str containing only lowercase characters. The task is to print the characters along with their frequencies in the order of their occurrence in the given string.Examples: Input: str = "geeksforgeeks" Output: g2 e4 k2 s2 f1 o1 r1Input: str = "helloworld" Output: h1 e1 l3 o2 w1 r1 d1 App
2 min read
Find the frequency of a digit in a number Given a number N and a digit D. Write a program to find how many times the digit D appears in the number N. Examples : Input: N = 1122322 , D = 2 Output: 4 Input: N = 346488 , D = 9 Output: 0 The idea to solve this problem is to keep extracting digits from the number N and check the extracted digits
4 min read
Mode of frequencies of given array elements Given an array arr[], the task is to find the mode of frequencies of elements of the given array. Examples: Input: arr[] = {6, 10, 3, 10, 8, 3, 6, 4}, N = 8Output: 2Explanation:Here (3, 10 and 6) have frequency 2, while (4 and 8) have frequency 1.Three numbers have frequency 2, while 2 numbers have
6 min read
Find array elements with frequencies in range [l , r] Given an array of integers, find the elements from the array whose frequency lies in the range [l, r]. Examples: Input : arr[] = { 1, 2, 3, 3, 2, 2, 5 } l = 2, r = 3 Output : 2 3 3 2 2 Approach : Take a hash map, which will store the frequency of all the elements in the array.Now, traverse once agai
9 min read