First Unique Character in String

Problem

Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.

For example:

s = "leetcode"
return 0.

s = "loveleetcode"
return 2.

Solution

class Solution:
    def firstUniqChar(self, s: str) -> int:
        freq = {}
        
        if not s:
            return -1
        
        for i in s:
            if i not in freq:
                freq[i] = 0
            freq[i]+=1
        
        for i in range(len(s)):
            if freq[s[i]] == 1:
                return i
        return -1

Last updated

Was this helpful?