Problem Statement
Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
Example 1:
Input: s = "leetcode" Output: 0 Explanation: 'l' is the first non-repeating character.
Example 2:
Input: s = "loveleetcode" Output: 2 Explanation: 'v' is the first non-repeating character.
Constraints:
sconsists of only lowercase English letters.
Approach (HashMap for General Characters)
- Count frequency using HashMap:
- Loop through the string
s. - For each character, store/update its count in a
HashMap<Character, Integer>.
- Loop through the string
- Find first unique character:
- Loop through
sagain. - For each character, check its count in the HashMap.
- Return the index of the first character with count
1.
- Loop through
- Return -1 if none found:
- If no character has count
1, return-1.
- If no character has count
Advantages:
- Works for any character, including uppercase letters, digits, or Unicode symbols.
- Simple and readable.
Java Code Solution (HashMap)
import java.util.HashMap;
import java.util.Map;
public class FirstUniqueCharacterGeneral {
public static int firstUniqChar(String s) {
Map<Character, Integer> freqMap = new HashMap<>();
// Step 1: Count frequency of each character
for (char c : s.toCharArray()) {
freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);
}
// Step 2: Find the first unique character
for (int i = 0; i < s.length(); i++) {
if (freqMap.get(s.charAt(i)) == 1) {
return i;
}
}
return -1; // No unique character found
}
public static void main(String[] args) {
String s = "aabb©xyz©";
int result = firstUniqChar(s);
System.out.println("Index of first unique character: " + result); // Output: 4 ('x')
}
}
Dry Run Example
Input:
s = "aabb©xyz©"
Step-by-step Execution:
- Count frequency in HashMap:
a -> 2 b -> 2 © -> 2 x -> 1 y -> 1 z -> 1
- Iterate over string to find first unique:
| Index | Char | Count | Is Unique? |
|---|---|---|---|
| 0 | a | 2 | No |
| 1 | a | 2 | No |
| 2 | b | 2 | No |
| 3 | b | 2 | No |
| 4 | © | 2 | No |
| 5 | x | 1 | Yes |
- Return 5 as the first unique character index.
Textual Diagram for Understanding
s = "aabb©xyz©" HashMap frequency: a:2, b:2, ©:2, x:1, y:1, z:1 Check string order: 0: a -> 2 -> skip 1: a -> 2 -> skip 2: b -> 2 -> skip 3: b -> 2 -> skip 4: © -> 2 -> skip 5: x -> 1 -> first unique -> return 5
Complexity Analysis
- Time Complexity: O(n)
- n = length of string.
- Two passes over the string: one for counting, one for checking.
- Space Complexity: O(n)
- HashMap stores count for all unique characters in
s.
- HashMap stores count for all unique characters in
