First Unique Character

Easy

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Examples

InputOutput
s = "leetcode"0
s = "aabb"-1

Python Solution

def first_uniq_char(s: str) -> int:
    counts = {}
    for c in s:
        counts[c] = counts.get(c, 0) + 1
    for i, c in enumerate(s):
        if counts[c] == 1:
            return i
    return -1

JavaScript Solution

function firstUniqChar(s) {
  const counts = {};
  for (const c of s) counts[c] = (counts[c] || 0) + 1;
  for (let i = 0; i < s.length; i++) {
    if (counts[s[i]] === 1) return i;
  }
  return -1;
}

Step-by-Step Explanation

  1. First pass: count frequency of each character.
  2. Second pass: find the first character with count 1.

Complexity Analysis

TimeO(n)
SpaceO(1)

Tags

StringHash Map

Related Problems

Related Tools

All Problems