When working with strings in Java, a very common interview and real-world problem is:
👉 “How do you find the first non-repeated character in a string?”
It sounds simple—but there are multiple ways to solve it efficiently, and choosing the right one can make a big difference in performance and readability.
In this blog, we’ll break it down step by step with easy explanations, optimized approaches, and code examples.
🔍 What Does “First Non-Repeated Character” Mean?
A non-repeated character is a character that appears only once in the string.
🧪 Example:
Input: "swiss"
Output: 'w'
Why?
-
s→ appears 3 times ❌ -
w→ appears once ✅ (first unique character) -
i→ appears once, but comes later
🧠 Approach 1: Using LinkedHashMap (Best for Interviews)
This is the most recommended approach because it maintains the insertion order.
✅ Code:
import java.util.*;
public class FirstNonRepeated {
public static void main(String[] args) {
String str = "swiss";
Map<Character, Integer> countMap = new LinkedHashMap<>();
// Count frequency
for (char c : str.toCharArray()) {
countMap.put(c, countMap.getOrDefault(c, 0) + 1);
}
// Find first non-repeated character
for (Map.Entry<Character, Integer> entry : countMap.entrySet()) {
if (entry.getValue() == 1) {
System.out.println("First non-repeated character: " + entry.getKey());
return;
}
}
System.out.println("No unique character found");
}
}
💡 Why This Works:
- Preserves order ✔️
- Easy to understand ✔️
- Time Complexity: O(n) ✔️
⚡ Approach 2: Using Frequency Array (Fastest)
If you’re dealing with ASCII characters, this is the fastest solution.
✅ Code:
public class FirstNonRepeated {
public static void main(String[] args) {
String str = "swiss";
int[] freq = new int[256];
// Count frequency
for (char c : str.toCharArray()) {
freq[c]++;
}
// Find first unique character
for (char c : str.toCharArray()) {
if (freq[c] == 1) {
System.out.println("First non-repeated character: " + c);
return;
}
}
System.out.println("No unique character found");
}
}
🚀 Advantages:
- Super fast ⚡
- Minimal memory overhead
- Best for performance-critical systems
🧪 Approach 3: Using Java 8 Streams (Modern Way)
Want a more functional programming style? Try this:
✅ Code:
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class FirstNonRepeated {
public static void main(String[] args) {
String str = "swiss";
Character result = str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(
Function.identity(),
LinkedHashMap::new,
Collectors.counting()
))
.entrySet()
.stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);
System.out.println("First non-repeated character: " + result);
}
}
⚠️ Note:
- More concise but slightly less readable for beginners
- Still maintains order using
LinkedHashMap
📊 Complexity Comparison
| Approach | Time Complexity | Space Complexity | Best Use Case |
|---|---|---|---|
| LinkedHashMap | O(n) | O(n) | Interviews, readability |
| Frequency Array | O(n) | O(1) | High performance |
| Java Streams | O(n) | O(n) | Modern Java style |
🎯 Key Takeaways
- Always clarify the problem: “first non-repeated” ≠ “first unique after sorting”
- Use LinkedHashMap for clarity and order preservation
- Use frequency array for speed
- Streams are great, but don’t overuse them in interviews
💬 Final Thoughts
This is a classic Java coding question that tests:
- Your understanding of data structures
- Your ability to optimize solutions
- Your code readability
Mastering this will help you crack coding interviews and write cleaner production code.
🔥 Bonus Tip
If the interviewer asks:
“What if the string is very large?”
👉 Answer:
- Use frequency array for best performance
- Avoid unnecessary object creation (like streams)
Top comments (0)