array and hashmap August 16, 2022

First unique character in a string

Time O(n) Space O(n) Open original problem

First we will count each character of the string. Then we iterate from the beginning, check which character has character count 1, return that. If we can't find anything with character count 1, we return -1.

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

Time Complexity: O(n)
Space Complexity: O(n)