🔹 Introduction
Java interviews often include string-based questions. One of the most commonly asked questions is:
👉 Find the first non-repeating character in a string.
In this article, we will solve it step by step in a simple and easy-to-understand way.
🔹 Problem Statement
Given a string, find the first character that does not repeat.
Example:
Input: aabbcde
Output: c
🔹 Approach
To solve this problem efficiently:
- Count frequency of each character
- Maintain insertion order
- Traverse again to find the first character with frequency = 1
👉 We use LinkedHashMap because:
- It maintains insertion order
- Helps us find the first non-repeating character
🔹 Java Code
import java.util.*;
public class FirstNonRepeating {
public static void main(String[] args) {
String str = "aabbcde";
Map<Character, Integer> map = new LinkedHashMap<>();
// Count frequency
for (char ch : str.toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
// Find first non-repeating
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() == 1) {
System.out.println("First non-repeating character: " + entry.getKey());
break;
}
}
}
}
🔹 Output
First non-repeating character: c
🔹 Time Complexity
- O(n) → Efficient solution
🔹 Key Takeaways
✔ Use LinkedHashMap to maintain order
✔ Two-pass solution is optimal
✔ Very commonly asked interview question
🔹 Conclusion
This is a must-know Java interview problem. Practice similar questions to strengthen your problem-solving skills.
Comments
Post a Comment