Given a string, the task is to write Java program to print all the duplicate characters with their frequency Example:
Input: str = “geeksforgeeks” Output: s : 2 e : 4 g : 2 k : 2 Input: str = “java” Output: a : 2
Approach: The idea is to do hashing using HashMap.
- Create a hashMap of type {char, int}.
- Traverse the string, check if the hashMap already contains the traversed character or not.
- If it is present, then increment the count or else insert the character in the hashmap with frequency = 1.
- Now traverse through the hashmap and look for the characters with frequency more than 1. Print these characters with their respective frequencies.
Below is the implementation of the above approach:
Java
import java.util.*;
class GFG {
public static void
countDuplicateCharacters(String str)
{
Map<Character, Integer> map
= new HashMap<Character, Integer>();
char [] charArray = str.toCharArray();
for ( char c : charArray) {
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1 );
}
else {
map.put(c, 1 );
}
}
for (Map.Entry<Character, Integer> entry :
map.entrySet()) {
if (entry.getValue() > 1 ) {
System.out.println(entry.getKey()
+ " : "
+ entry.getValue());
}
}
}
public static void
main(String args[])
{
String str = "geeksforgeeks" ;
countDuplicateCharacters(str);
}
}
|
Output:s : 2
e : 4
g : 2
k : 2
Time Complexity: O(NlogN)
Auxiliary Space: O(N) since using Map