Find duplicates Characters in the given String

Objective: Given a string, write an algorithm to find all the duplicate characters in the string and print its count.

Example:

Input String: tutorial horizon
Output: Duplicate Characters: 
r - 2
t - 2
i - 2
o – 3

Approach: Hash Map

  • Maintain a Hash Map with Character as key and count as value.
  • Iterate through string, one character at a time.
  • Check if character is present in hashmap, if yes then increment the count of the character in the hashmap and if character is not present in hashmap then insert it with count 1.
  • Once iteration of string is completed, iterate the Hashmap and print all the characters with count > 1.

Java Code:

Output:

Duplicate Characters: 
r - 2
t - 2
i - 2
o - 3

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

%d bloggers like this: