sagelearnai

First Unique Character in a String

Difficulty: Easy · Pattern: Hashing · LeetCode #387

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

Examples

text
"leetcode"      →  0
"loveleetcode"  →  2
"aabb"          →  −1

Hints

  1. Two passes: count frequencies, then find the first with count 1.

Approach

Count each character's occurrences, then scan s from the left and return the first index whose character has count 1. O(n), O(alphabet).

Complexity

Time: O(n). Space: O(alphabet).

Python solution
from collections import Counter

def firstUniqChar(s):
    c = Counter(s)
    for i, ch in enumerate(s):
        if c[ch] == 1:
            return i
    return -1
JavaScript solution
function firstUniqChar(s) {
  const c = new Map();
  for (const ch of s) c.set(ch, (c.get(ch) || 0) + 1);
  for (let i = 0; i < s.length; i++) if (c.get(s[i]) === 1) return i;
  return -1;
}