
Java Programming
June 7, 2025 at 08:59 AM
*Java Coding Challenge: Part 20 – Find the First Repeating Character in a String*
*Challenge:*
Write a Java program to find the first repeating character in a string.
*Example:*
Input: "programming"
Output: 'r'
(‘r’ is the first character that repeats)
*Approach:*
1. Traverse the string one character at a time.
2. Use a HashSet to track seen characters.
3. The first character that’s already in the set is the answer.
*Java Code:*
import java.util.HashSet;
public class FirstRepeatingChar {
public static void main(String[] args) {
String input = "programming";
char result = findFirstRepeatingChar(input);
if (result != '\0') {
System.out.println("First repeating character: " + result);
} else {
System.out.println("No repeating character found.");
}
}
public static char findFirstRepeatingChar(String str) {
HashSet seen = new HashSet<>();
for (char ch : str.toCharArray()) {
if (seen.contains(ch)) {
return ch;
}
seen.add(ch);
}
return '\0'; // null character if no repeating character is found
}
}
If you want to find the first non-repeating character, use a LinkedHashMap to preserve the order and count frequency.
*React ❤️ for Part 21*
❤️
❤
👍
♥
🇮🇳
😂
😮
🙏
🪡
52