In this post, we’ll write a Java program to find the first non-repeated character in a string. This is a popular question in coding interviews to test your understanding of string manipulation and hashing.
๐ Problem Statement
Given a string, find the first character that does not repeat anywhere else in the string. Return that character.
๐ Example
- Input:
"programming"→ Output: 'p' - Input:
"aabbcc"→ Output: No unique character
✅ Java Program Using LinkedHashMap
import java.util.LinkedHashMap;
import java.util.Map;
public class FirstUniqueCharacter {
public static void main(String[] args) {
String input = "programming";
Character result = findFirstNonRepeated(input);
if(result != null)
System.out.println("First non-repeated character is: " + result);
else
System.out.println("No unique character found.");
}
static Character findFirstNonRepeated(String str) {
Map charCount = new LinkedHashMap<>();
for (char c : str.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
for (Map.Entry entry : charCount.entrySet()) {
if (entry.getValue() == 1)
return entry.getKey();
}
return null;
}
}
✅ Output
First non-repeated character is: p
๐ง Interview Tip
This question can be optimized by using LinkedHashMap for maintaining order. Make sure you explain your choice of data structures clearly.
๐ Conclusion
We’ve learned how to find the first non-repeated character in a string using Java. This logic is commonly used in interviews and string-based challenges.
๐ Master Java String & Frequency-Based Problems
Finding the first non-repeated character is a common Java interview and coding-round problem. Strengthen your string manipulation and HashMap-based logic by exploring these closely related problems and interview resources.
๐ง Java Coding Round Questions
Practice frequently asked string and HashMap-based problems.
๐งต Java String Pool & Interning
Understand how strings are stored and why immutability matters.
๐ฆ Java Collections Interview Questions
Learn how HashMap and LinkedHashMap are used in real interview problems.
๐ Palindrome String Program
Another classic string comparison problem asked in interviews.
๐ Reverse String in Java
Strengthen your understanding of string traversal techniques.
๐ข String Contains Only Digits
Practice validation-based string processing problems.
๐งฎ Check Anagram Strings
Learn character frequency comparison using arrays and maps.
๐ Character Occurrence Count
Understand frequency counting as a foundation for many string problems.
๐ฏ Java Interview Questions (Freshers)
Common interview questions involving strings and collections.
๐งช Advanced Java Programs (Real-World)
Apply string processing logic in real-world Java scenarios.