VOOZH about

URL: https://www.geeksforgeeks.org/dsa/java-program-to-print-all-duplicate-characters-in-a-string/

⇱ Java program to print all duplicate characters in a string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java program to print all duplicate characters in a string

Last Updated : 15 Jul, 2025

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:

Output:
s : 2
e : 4
g : 2
k : 2

Time Complexity: O(NlogN) 

Auxiliary Space: O(N) since using Map

Comment