Problem statement

https://leetcode.com/problems/first-unique-character-in-a-string/

Solution

We can not do better than O(n), because we need to iterate over all string and count all frequencies. We can do it with Counter(s) in python. Then we iterate list once again and return the first symbol for which frequency is 1.

Complexity

Time complexity is O(n), space complexity is O(1).

Code

class Solution:
    def firstUniqChar(self, s):
        count = Counter(s)

        for num, char in enumerate(s):
            if count[char] == 1: return num
        return -1