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
0
The counts are l:1, e:3, t:1, c:1, o:1, d:1, and l at index 0 is the earliest with a count of 1.

Example 2

Input
s = "aabb"
Output
-1
Both a and b appear 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
Step through firstUniqueChar("leetcode") call by call