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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem