 Open in App
Not now

# Group all occurrences of characters according to first appearance

• Difficulty Level : Easy
• Last Updated : 06 Jul, 2022

Given a string of lowercase characters, the task is to print the string in a manner such that a character comes first in string displays first with all its occurrences in string.

Examples:

```Input : str = "geeksforgeeks"
Output:  ggeeeekkssfor
Explanation: In the given string 'g' comes first
and occurs 2 times so it is printed first
Then 'e' comes in this string and 4 times so
it gets printed. Similarly remaining string is
printed.

Input :  str = "occurrence"
output : occcurreen

Input  : str = "cdab"
Output : cdab```

This problem is a string version of following problem for array of integers. Group multiple occurrence of array elements ordered by first occurrences Since given strings have only 26 possible characters, it is easier to implement for strings.

Implementation:

1. Count the occurrence of all the characters in given string using an array of size 26.
2. Then start traversing the string. Print every character its count times.

## C++

 `// C++ program to print all occurrences of every character``// together.``# include``using` `namespace` `std;` `// Since only lower case characters are there``const` `int` `MAX_CHAR = 26;` `// Function to print the string``void` `printGrouped(string str)``{``    ``int` `n = str.length();` `    ``// Initialize counts of all characters as 0``    ``int`  `count[MAX_CHAR] = {0};` `    ``// Count occurrences of all characters in string``    ``for` `(``int` `i = 0 ; i < n ; i++)``        ``count[str[i]-``'a'``]++;` `    ``// Starts traversing the string``    ``for` `(``int` `i = 0; i < n ; i++)``    ``{``        ``// Print the character till its count in``        ``// hash array``        ``while` `(count[str[i]-``'a'``]--)``            ``cout << str[i];` `        ``// Make this character's count value as 0.``        ``count[str[i]-``'a'``] = 0;``    ``}``}` `// Driver code``int` `main()``{``    ``string str = ``"geeksforgeeks"``;` `    ``printGrouped(str);` `    ``return` `0;``}`

## Java

 `// C++ program to print all occurrences of every character``// together.``import` `java.io.*;``import` `java.util.*;` `class` `GFG``{``    ``// Since only lower case characters are there``    ``static` `int` `MAX_CHAR = ``26``;``     ` `    ``// Function to print the string``    ``static` `void` `printGrouped(String str)``    ``{``        ``int` `n = str.length();``     ` `        ``// Initialize counts of all characters as 0``        ``int` `count[] = ``new` `int``[MAX_CHAR];``        ``Arrays.fill(count,``0``);``     ` `        ``// Count occurrences of all characters in string``        ``for` `(``int` `i = ``0` `; i < n ; i++)``            ``count[str.charAt(i)-``'a'``]++;``     ` `        ``// Starts traversing the string``        ``for` `(``int` `i = ``0``; i < n ; i++)``        ``{``            ``// Print the character till its count in``            ``// hash array``            ``while` `(count[str.charAt(i)-``'a'``]-->``0``)``                ``System.out.print(str.charAt(i));``     ` `            ``// Make this character's count value as 0.``            ``count[str.charAt(i)-``'a'``] = ``0``;``        ``}``    ``}``    ` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``String str = ``"geeksforgeeks"``;`` ` `        ``printGrouped(str);``    ``}``}` `// This code is contributed by shruti456rawal`

## Python3

 `# Python3 program to print all occurrences``# of every character together.` `# Since only lower case characters are there``MAX_CHAR ``=` `26` `# Function to print the string``def` `printGrouped(string):``    ``n ``=` `len``(string)` `    ``# Initialize counts of all characters as 0``    ``count ``=` `[``0``] ``*` `MAX_CHAR` `    ``# Count occurrences of all characters in string``    ``for` `i ``in` `range``(n):``        ``count[``ord``(string[i]) ``-` `ord``(``"a"``)] ``+``=` `1` `    ``# Starts traversing the string``    ``for` `i ``in` `range``(n):` `        ``# Print the character till its count in``        ``# hash array``        ``while` `count[``ord``(string[i]) ``-` `ord``(``"a"``)]:``            ``print``(string[i], end ``=` `"")``            ``count[``ord``(string[i]) ``-` `ord``(``"a"``)] ``-``=` `1` `        ``# Make this character's count value as 0.``        ``count[``ord``(string[i]) ``-` `ord``(``"a"``)] ``=` `0` `# Driver code``if` `__name__ ``=``=` `"__main__"``:``    ``string ``=` `"geeksforgeeks"``    ``printGrouped(string)` `# This code is contributed by``# sanjeev2552`

## C#

 `// C# program to print all``// occurrences of every``// character together.``using` `System;` `class` `GFG``{``    ``// Since only lower case``    ``// characters are there``    ``static` `int` `MAX_CHAR = 26;``    ` `    ``// Method to print``    ``// the string``    ``static` `void` `printGrouped(String str)``    ``{``        ``int` `n = str.Length;``    ` `        ``// Initialize counts of``        ``// all characters as 0``        ``int` `[]count = ``new` `int``[MAX_CHAR];``    ` `        ``// Count occurrences of``        ``// all characters in string``        ``for` `(``int` `i = 0 ; i < n ; i++)``            ``count[str[i] - ``'a'``]++;``    ` `        ``// Starts traversing``        ``// the string``        ``for` `(``int` `i = 0; i < n ; i++)``        ``{``            ``// Print the character``            ``// till its count in``            ``// hash array``            ``while` `(count[str[i] - ``'a'``] != 0)``            ``{``                ``Console.Write(str[i]);``                ``count[str[i] - ``'a'``]--;``            ``}``    ` `            ``// Make this character's``            ``// count value as 0.``            ``count[str[i] - ``'a'``] = 0;``        ``}``    ``}``    ` `    ``// Driver code``    ``public` `static` `void` `Main()``    ``{``        ``string` `str = ``"geeksforgeeks"``;``        ``printGrouped(str);``    ``}``}` `// This code is contributed by Sam007`

## Javascript

 `// javascript program to print all occurrences of every character``// together.` `var` `MAX_CHAR = 26;` `// Function to print the string``function` `printGrouped(str)``{``    ``var` `n = str.length;``    ``// Initialize counts of all characters as 0``    ``var` `count = Array(MAX_CHAR).fill(0);``    ``// Count occurrences of all characters in string``    ``for` `(``var` `i=0; i < n; i++)``    ``{``        ``count[str.charAt(i).charCodeAt(0) - ``'a'``.charCodeAt(0)]++;``    ``}``    ``// Starts traversing the string``    ``for` `(``var` `i=0; i < n; i++)``    ``{``        ``// Print the character till its count in``        ``// hash array``        ``while` `(count[str.charAt(i).charCodeAt(0) - ``'a'``.charCodeAt(0)]-- > 0)``        ``{``            ``console.log(str.charAt(i));``        ``}``        ``// Make this character's count value as 0.``        ``count[str.charAt(i).charCodeAt(0) - 'a'.charCodeAt(0)] = 0;``    ``}``}``// Driver Code``    ` `var` `str = ``"geeksforgeeks"``;``printGrouped(str);` `// This code is contributed by Aarti_Rathi`

Output

`ggeeeekkssfor`

Time complexity : O(n)
Auxiliary Space : O(1)

This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

My Personal Notes arrow_drop_up