Find First Repeating Character in a String in Java
The first repeating character in a string is the character that appears more than once and whose second occurrence comes first in the string order.
This problem is commonly asked in interviews and helps improve understanding of string traversal and character frequency.
How the Logic Works
- Create a frequency array to track visited characters.
- Traverse the string from left to right.
- If a character is seen again, it is the first repeating character.
- Stop the traversal immediately.
Example 1
Input: "programming"
- p → first time
- r → first time
- o → first time
- g → first time
- r → repeated ✖
First Repeating Character: r
Example 2
Input: "abcdef"
Result: No repeating character found
Java Program to Find First Repeating Character
import java.util.Scanner;
public class FirstRepeatingCharacter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine().toLowerCase();
boolean[] visited = new boolean[256];
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == ' ') {
continue;
}
if (visited[ch]) {
System.out.println("First Repeating Character: " + ch);
return;
}
visited[ch] = true;
}
System.out.println("No repeating character found");
}
}
Sample Output
Enter a string: coding
No repeating character found
Enter a string: interview
First Repeating Character: i
Important Notes
- Spaces are ignored.
- Program is case-insensitive.
- Traversal stops as soon as a repeat is found.
Practice Challenges
- Find the first repeating character without using extra space.
- Find the last repeating character.
- Print all repeating characters in order of appearance.
Finding the first repeating character improves your ability to optimize string traversal and early termination logic.