Find Duplicate Characters in a String | Java Code

Given an input string, Write a java code to find duplicate characters in a String.

For example :

Example 1:

Input    : “Java”
Output : a

The character a appears more than once in a string.

Example 2:

Input : “programming”
Output : m,g,r

These three characters (m, g, r) appears more than once in a string.

Find duplicate characters in a string

In this tutorial, I am going to explain multiple approaches to solve this problem..

Find Duplicate Characters in a String using HashMap

In this example, I am using HashMap to print duplicate characters in a string.The time complexity of get and put operation in HashMap is O(1). That’s the reason we are using this data structure.

In HashMap, we store key and value pairs. So, in our case key is the character and value is it’s count. Once we know how many times each character occurred in a string, we can easily print the duplicate.

Any character which appears more than once in a string is a duplicate character.

The time complexity of this approach is O(1) and it’s space complexity is also O(1).

Find duplicate characters in a string video tutorial

Java program to reverse a string using stack

Find Duplicate Characters in a String using Set

In the last example, we have used HashMap to solve this problem.  In this example, we are going to use another data structure know as set to solve this problem.

The set data structure doesn’t allow duplicates and lookup time is O(1) . Using this property we can easily return duplicate characters from a string in java.

Here are the steps –

i) Declare a set which holds the value of character type.

ii) Traverse a string and put each character in a string. If the character is already present in a set, it means it’s a duplicate character.

The time complexity of this approach is O(n) and it’s space complexity is also O(n).

Java program to reverse each words of a string

Video Tutorial

In this video tutorial, I have explained multiple approaches to solve this problem.

Find duplicate characters in a string video tutorial

Tagged , , , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.