Hide sidebar

First Unique Character in a String

Hashing
EasyLeetCode #387
15 min

Problem Statement

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

Example

Example 1:

Input: s = "leetcode"

Output: 0

Solution (Hash Map)

A hash map can be used to store the frequency of each character. We can iterate through the string once to build the frequency map, and then a second time to find the first character with a frequency of 1.

Algorithm Steps

  • Create a hash map to store character counts.
  • Iterate through the string to populate the hash map with character frequencies.
  • Iterate through the string again. For each character, check its count in the hash map.
  • If the count is 1, return the current index.
  • If the loop completes without finding a unique character, return -1.

String

l
e
e
t
c
o
d
e

Character Counts

Start. First, count character frequencies.
First Unique Character in a String Solution

from collections import Counter

class Solution:
    def firstUniqChar(self, s: str) -> int:
        count = Counter(s)
        for i, c in enumerate(s):
            if count[c] == 1:
                return i
        return -1