🔹 Introduction
Finding duplicate characters in a string is a frequently asked Java interview question.
It helps test your understanding of strings, HashMap, and Java Streams.
👉 In this article, we will explore 3 different approaches to solve this problem.
🔹 Problem Statement
Given a string, find all duplicate characters.
Example:
Input: programming
Output: r, g, m
🔹 Approach 1: Using HashMap (Most Asked)
💡 Explanation
- Count frequency using HashMap
- Print characters with frequency > 1
👨💻 Java Code
import java.util.*;
public class DuplicateCharacters {
public static void main(String[] args) {
String str = "programming";
Map<Character, Integer> map = new HashMap<>();
for (char ch : str.toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(entry.getKey());
}
}
}
}
🔹 Approach 2: Using Set
💡 Explanation
- Use one set to track seen characters
- Another set to store duplicates
👨💻 Java Code
import java.util.*;
public class DuplicateCharacters {
public static void main(String[] args) {
String str = "programming";
Set<Character> seen = new HashSet<>();
Set<Character> duplicates = new HashSet<>();
for (char ch : str.toCharArray()) {
if (!seen.add(ch)) {
duplicates.add(ch);
}
}
duplicates.forEach(System.out::println);
}
}
🔹 Approach 3: Using Java Streams (Advanced)
💡 Explanation
- Convert string into stream
- Use groupingBy + counting
- Filter duplicates
👨💻 Java Code
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class DuplicateCharacters {
public static void main(String[] args) {
String str = "programming";
Map<Character, Long> map =
str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()
));
map.entrySet().stream()
.filter(entry -> entry.getValue() > 1)
.forEach(entry -> System.out.println(entry.getKey()));
}
}
🔹 Output
r
g
m
🔹 Time Complexity
- O(n) for all approaches
🔹 Key Takeaways
✔ HashMap is most important for interviews
✔ Set approach is clean and efficient
✔ Streams show advanced knowledge
🔹 Conclusion
This is a must-know Java interview problem.
Understanding multiple approaches helps you stand out in interviews.
🔗 Also Read
👉 First Non-Repeating Character in Java
👉 Check Palindrome String in Java
👉 Reverse a String
👉 Count Character Frequency in Java
Comments
Post a Comment