TARGET DECK: Leetcode FILE TAGS: Easy


Intuition

  • First, check the count of the string.
  • Then check the characters of count 1, and return the first occurrence of that.
  • Pretty straight forward using a counter.

Complexity

Runtime

Space

due to the counter, where N is the number of characters.

Code

Using Counter

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

Using a Set

class Solution:
    def firstUniqChar(self, s: str) -> int:
        s_set = set(s)
        exists = [False] * 26
        for i, c in enumerate(s):
            ordinal_rep = ord(c) - ord('a')
            if exists[ordinal_rep] and c in s_set:
                s_set.remove(c)
            exists[ordinal_rep] = True
 
        for i, c in enumerate(s):
            if c in s_set:
                return i        
        return -1

Cards

START Basic Front: First Unique Character In A String Back: Use a Counter.

END


References