First pass: count each letter. Second pass in order: the first character with count 1 wins.
Approach 1
class Solution {
public int firstUniqChar(String s) {
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) count[s.charAt(i) - 'a']++;
for (int i = 0; i < s.length(); i++) if (count[s.charAt(i) - 'a'] == 1) return i;
return -1;
}
}
Verdict: Two linear passes.
Before you submit
Edge cases and common mistakes
Test these inputs
One character → 0
No unique character → −1
The unique character is last
Mistakes people make
Returning the first character with count 1 in alphabet order instead of string order.
Interview
Follow-up questions
What if characters arrive as a stream and you must answer after each one?