First Unique Character in a String

Easy

Problem

Return the index of the first character that appears exactly once in the string, or −1 if there is none.

Example 1

Input:  "leetcode"
Output: 0

Example 2

Input:  "loveleetcode"
Output: 2

Example 3

Input:  "aabb"
Output: -1

Test cases

Case 1

Input:    "leetcode"
Expected: 0

Case 2

Input:    "loveleetcode"
Expected: 2

Case 3

Input:    "aabb"
Expected: -1

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Two passes with a count

Time O(n)Space O(1) — alphabet size

Count every character, then return the first index whose count is 1.

function firstUniqChar(s) {
const cnt = new Map();
for (const c of s) cnt.set(c, (cnt.get(c) ?? 0) + 1);
for (let i = 0; i < s.length; i++) if (cnt.get(s[i]) === 1) return i;
return -1;
}