How to write a program that detects duplicate letters in a string

Problem statement

Given a string, we need to check whether it has duplicate letters in it. The output should be true if the string has duplicates, and false otherwise.

Note: The string contains only letters.

Example 1:

  • Input: str="educative"
  • Output: true

As there are duplicate letters in the string, the output is true.

Example 2:

  • Input: str="answer"
  • Output: false

As there are no duplicate letters in the string, the output is false.

Solution

The solution is to use a set data structure that maintains the already seen letters.

The steps of the algorithm are as follows:

  1. Loop through the letters of the string. For every letter, perform the following steps:
    • Check if the set contains the given letter.
    • If yes, print true and exit.
    • If no, continue the loop.
  2. If the control has reached this point, then there are no duplicate letters in the string. Print false now.

Code

import java.util.HashSet;
import java.util.Set;
class Main{
public static boolean duplicateExists(String text){
Set<Character> characters = new HashSet<>();
for(char ch: text.toCharArray()){
if(characters.contains(ch)) return true;
characters.add(ch);
}
return false;
}
public static void main(String[] args) {
String text = "educative";
System.out.println(duplicateExists(text));
}
}

Explanation

  • Lines 1–2: We import Set and HashSet.
  • Lines 6–13: We define a function called duplicateExists() that takes a string and checks for duplicate characters or letters.
  • Line 16: We define a string called text.
  • Line 17: We invoke a duplicateExists() method with text as the string.

Free Resources