First Non-Repeating Character in Java: Solution, Explanation & Practice
Find the first character that does not repeat
Problem summary
Write a program that finds the first character that appears only once in a string.
Starter code
public class Main {
public static void main(String[] args) {
String text = "programming"; // Test case 1
// Find first non-repeating character
// Print: First unique: <char> OR No unique character
}
}Expected output and test cases
- p is first unique
First unique: p
- First unique in aabbc
First unique: a
- All repeat
No unique character
Hints
- Count occurrence of each character first
- Then find first with count 1
- Can use array of size 26 for counts
Validated solution
Reveal Java solution
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
static Character firstUnique(String text) {
Map<Character, Integer> counts = new LinkedHashMap<>();
for (char ch : text.toCharArray()) counts.put(ch, counts.getOrDefault(ch, 0) + 1);
for (char ch : text.toCharArray()) if (counts.get(ch) == 1) return ch;
return null;
}
public static void main(String[] args) {
Character unique = firstUnique("aabbp");
System.out.println(unique == null ? "No unique character" : "First unique: " + unique);
}
}How to approach the problem
First count every character, then scan in original order to find the first count of one. Separating counting from selection avoids prematurely choosing a character that later repeats.
Approach
- Build a frequency map.
- Keep the original order for the second pass.
- Return no result when every count exceeds one.
Time and space complexity
Time: O(n). Space: O(k), where k is the number of distinct characters.
Edge cases to test
- An empty String has no unique character.
- Case-sensitive and case-insensitive behavior are different contracts.
Common mistakes
- Returning the first newly seen character before the full count is known.
- Using HashMap iteration order as if it represented text order.
Follow-up challenge
Find the first non-repeating Unicode code point rather than char.
Related Strings exercises
Practice all Strings exercises · Run this idea in the Java compiler