Skip to main content

387. First Unique Character in a String

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

Python

First Solution

  • Time: O(N^2)
  • Space: O(M) # M for duplicated chars count
class Solution:
def firstUniqChar(self, s: str) -> int:
cur = 0
seem = set()

while cur < len(s):
char = s[cur]
if char in seem:
cur += 1
continue

if char not in s[cur+1:]:
return cur

seem.add(char)
cur += 1
return -1

Second Solution

  • Time: O(N)
  • Space: O(M)
from collections import Counter


class Solution:
def firstUniqChar(self, s: str) -> int:
counts = Counter(s)

uniq_chars = [c for c, v in counts.items() if v == 1]

if not uniq_chars:
return -1

return min([s.index(c) for c in uniq_chars])