Find First Non-Repeating Character in a String in Java
The first non-repeating character is the character that appears only once in the string and whose occurrence comes first.
This problem is frequently asked in interviews and helps understand character frequency and ordered traversal of strings.
How the Logic Works
- Create a frequency array to count each character.
- Traverse the string and update character counts.
- Traverse the string again from left to right.
- The first character with frequency 1 is the answer.
Example 1
Input: "programming"
- p → 1
- r → 2
- o → 1
- g → 2
- a → 1
First Non-Repeating Character: p
Example 2
Input: "aabbcc"
Result: No non-repeating character found
Java Program to Find First Non-Repeating Character
import java.util.Scanner;
public class FirstNonRepeatingCharacter {
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++) {
char ch = str.charAt(i);
if (ch != ' ') {
freq[ch]++;
}
}
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != ' ' && freq[ch] == 1) {
System.out.println("First Non-Repeating Character: " + ch);
return;
}
}
System.out.println("No non-repeating character found");
}
}
Sample Output
Enter a string: interview
First Non-Repeating Character: n
Enter a string: aabb
No non-repeating character found
Important Notes
- Spaces are ignored.
- Program is case-insensitive.
- Time complexity is O(n).
Practice Challenges
- Find the first non-repeating character without using extra space.
- Print all non-repeating characters.
- Find the last non-repeating character.
Finding non-repeating characters improves your understanding of frequency analysis and string traversal techniques in Java.