Two different ways in Java to find all duplicate string characters

Java program to find all duplicate characters in a string:

In this post, we will learn two different ways to find all duplicate characters in a user-input string in Java. For example, if the word is hello, the program will print l as this is the only duplicate character.

We can either use two loops and compare each character with all other characters. Or, we can iterate the characters only once and keep tracking the counts of each character in a hashmap. If the count is 2, it will print that character.

Method 1: By using two for loops:

With this method, we will use two for loops. The outer loop will iterate through each character of the string one by one and the inner loop will iterate through all other characters to the right of the outer loop character. We will use a Set to hold all duplicate characters.

Below is the complete program:

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

class Main {
    public static void main(String[] args) {
        String str;
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter the string: ");
        str = scanner.nextLine();

        Set<Character> duplicateChars = new HashSet<>();

        for (int i = 0; i < str.length(); i++) {
            for (int j = i + 1; j < str.length(); j++) {
                if (str.charAt(i) == str.charAt(j)) {
                    duplicateChars.add(str.charAt(i));
                }
            }
        }

        System.out.println("Duplicate characters are: ");
        for (Character c : duplicateChars) {
            System.out.println(c);
        }
    }
}

Here,

  • str is the string variable to hold the string.
  • The scanner object is used to read a user input string. It takes the string as an input from the user and stores it in the str variable.
  • We are creating a Set of Characters to hold all the characters. Using a set has many advantages because we can’t add duplicate characters to a set. So, if there are duplicate characters, it will add that character only once.
  • Two for loops are used. The outer loop runs for each character of the string one by one. The inner loop compares the current character pointed by the outer loop with all other characters next to it. If it finds that the character pointed by the outer loop is equal to the character pointed by the inner loop, it adds that character to the set duplicateChars. As I explained above, even if we find the same character multiple times, it will add it only once.
  • The last for loop is used to print the content of the set i.e. all duplicate characters found.

If you run this program, it will print output as like below:

Enter the string: 
abcdabcdabcd
Duplicate characters are: 
a
b
c
d

Enter the string: 
helloworld
Duplicate characters are: 
l
o

Enter the string: 
hello world hello
Duplicate characters are: 
 
e
h
l
o

Method 2: With one iteration:

In the above example, we have to iterate through the remaining characters again and again for each character the outer loop is pointing. We can also iterate through the string characters only once and find out the duplicate characters.

To do that, we have to store the count of each character of the string while iterating. We will use a HashTable to do that. If the count is 2, it will be printed to the user. If it is more than 2, we will ignore it because it is already printed before.

So, this way will iterate through the characters only once and print the duplicate characters. Below is the complete program:

import java.util.Hashtable;
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        String str;
        Character c;
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter the string: ");
        str = scanner.nextLine();

        Hashtable<Character, Integer> characterMap = new Hashtable<>();

        System.out.println("Duplicate characters are: ");

        for (int i = 0; i < str.length(); i++) {
            c = str.charAt(i);
            if (characterMap.containsKey(c)) {
                characterMap.put(c, characterMap.get(c) + 1);
            } else {
                characterMap.put(c, 1);
            }

            if (characterMap.get(c) == 2) {
                System.out.println(c);
            }
        }
    }
}

Here,

  • The string is read and stored in the variable str
  • characterMap is a Hashtable to hold the count of each character.
  • The for loop is iterating through the characters of the string one by one.
    • For each character, it checks if the character is in the Hashtable or not.
    • If yes, we are incrementing the count by 1
    • Else, we are storing that character with value 1
    • The if block checks if the current value of the current character is 2 or not. If yes, it prints that character.

If you run this program, it will print similar output as the above program.

You might also like: