Maintained by Vikas Dulgunde, software engineer
You are handed a string made up of lowercase English letters. Your job is to locate the earliest position where a character appears only one time across the whole string.
The word 'first' refers to position, not value. A character counts as unique only when its total number of occurrences in the entire string is one. The very first such character, read left to right, is the answer.
Return that character's zero-based index. When no character qualifies, meaning every letter appears at least twice, return -1.
The letter 'l' at index 0 appears once in the whole string, so it is the first non-repeating character.
'l' and 'o' both repeat, but 'v' at index 2 appears only once, making it the earliest unique character.
Both 'a' and 'b' appear twice, so there is no character that occurs exactly once and the answer is -1.
Visible test cases
You cannot decide whether a character is unique by looking at it once. You need to know its total count across the whole string before judging any single position.
Make one pass to tally how many times each character appears, then a second pass to find the earliest position whose tally is exactly one.
Because the alphabet is fixed at 26 letters, the frequency table has a constant size, so the count storage does not grow with the input length.
For each position, rescan the rest of the string to check whether that character appears anywhere else.
Count each character once, then walk left to right and return the first index whose character has a count of one.