First non-repeating character
Easy TimeO(n) SpaceO(1)
Given a string s, return the index of the first character that appears exactly once in it, or -1 when every character repeats. A character counts as repeating if it appears again anywhere in the string, however far away. It is the earliest such character that is wanted, not any of them, and the answer is its position rather than the character itself.
Examples
Example 1
- Input
- s = "leetcode"
- Output
- The counts are l:1, e:3, t:1, c:1, o:1, d:1, and
0lat index 0 is the earliest with a count of 1.
Example 2
- Input
- s = "aabb"
- Output
- Both
-1aandbappear twice, so no count is ever 1.
The Code
function firstUniqueChar(s) {
const counts = new Map();
for (let i = 0; i < s.length; i++) {
counts.set(s[i], (counts.get(s[i]) || 0) + 1);
}
for (let i = 0; i < s.length; i++) {
if (counts.get(s[i]) === 1) return i;
}
return -1;
}
firstUniqueChar("leetcode");Done
More like this
All strings examples (13) →- Reverse words Split on whitespace, walk backwards, join again.
- Valid anagram Count letters up with one word, down with the other.
- Common prefix Start with the whole first word, shrink until everything matches.
- Run-length encoding Collapse each run of repeats into a character and a count.
- Longest unique substring A sliding window that jumps forward past any repeat.
- Caesar cipher Rotate each letter through the alphabet and wrap around.