First Unique Character in a String [leetcode easy]

Leetcode387

Example,

Question: Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.
Input: “leetcode”
Output: 0

Solution 1: Store the count of the characters in a dictionary, then iterate through the string and return the first count of value 1

time complexiity: O(n)
space complexity: O(n)
runtime: 200 ms | faster than 15.35% submissions
memory: 13.1 MB | less than 97.83% submissions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def firstUniqChar(self, s: str) -> int:

char = {}

for i in range(len(s)):
if not char.get(s[i]):
char[s[i]] = 1
else:
char[s[i]] += 1

for i in range(len(s)):
if char.get(s[i]) == 1:
return i

return -1

Solution 2: Of course using built in function is faster AF; iterate through all the letters and track the first index of the string if the letter is unique in the string

time complexiity: O(n)
space complexity: O(n)
runtime: 40 ms | faster than 99.30% submissions
memory: 13.1 MB | less than 97.83% submissions

1
2
3
4
5
6
7
8
def firstUniqChar(self, s: str) -> int:
index = [] # O(1) since it's always 26 letters
letters='abcdefghijklmnopqrstuvwxyz'
for i in letters: # O(1) since it's always 26 letters
if s.count(i) == 1: # O(n)
index.append(s.index(i)) # string.index is O(n)

return min(index) if len(index) > 0 else -1

Apparently,

26N < 2N. I’m still too noob.

Are there anyone,

coming back to track my progress? Or could it be just my multiple browsers and devices ballooning my GA? HAHA. The submission metrics seem cool,but it might not be accurate if the number of submissions are low.