Find Duplicate Characters in a String in Java
Finding duplicate characters in a string means identifying characters that appear more than once. This problem is commonly asked in interviews and helps in understanding character frequency and string traversal.
Duplicate character detection is useful in:
- Data validation
- Password strength checking
- Text analysis
How the Logic Works
- Create a frequency array to store character counts.
- Traverse the string character by character.
- Increment the count for each character.
- Print characters whose count is greater than 1.
Example 1
Input: "programming"
Duplicate Characters:
- r
- g
- m
Example 2
Input: "Java"
Duplicate Characters:
- a
Java Program to Find Duplicate Characters
import java.util.Scanner;
public class DuplicateCharacters {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine().toLowerCase();
int[] freq = new int[256];
for (int i = 0; i < str.length(); i++) {
freq[str.charAt(i)]++;
}
System.out.println("Duplicate Characters:");
for (int i = 0; i < 256; i++) {
if (freq[i] > 1 && i != ' ') {
System.out.println((char) i);
}
}
}
}
Sample Output
Enter a string: interview
Duplicate Characters:
i
e
Important Notes
- Program is case-insensitive.
- Spaces are ignored.
- Time complexity is O(n).
Practice Challenges
- Print duplicate characters with their frequency.
- Find duplicate characters without using arrays.
- Print only the first repeating character.
Duplicate character detection strengthens your understanding of frequency counting and efficient string processing in Java.