Home > leetcode > First Unique Character in a String (Python)

First Unique Character in a String (Python)


Today we solve a very popular 'kata' on Leetcode #387 First Unique Character in a String

Difficulty level: Easy

Related Topics: Hash Table, String

Disclaimer: You might have different results in Runtime and Memory Usage, it's okay 🤣 it how it works.


Description:

Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode"
return 2.

Note:

 You may assume the string contains only lowercase English letters.

And your playground looks like this:

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

Solution 1

We know that we can get an empty string. Let's first check it, then start to search for unique characters.

If string has no length, that means it's empty and we return -1

    if(len(s) != 0):

    ...

    return -1

Then we declare an empty dictionary

hash_table = {}

And count how many times a character appears.

If we have a character in the dictionary we increase its value by one, if not the value will be equal to one.

 for char in s:
    if char in hash_table:
        hash_table[char] = hash_table[char] + 1
    else:
        hash_table[char] = 1

Then we go thru the dictionary and return the first character which has value 1

for i, char in enumerate(s):
    if hash_table[char] == 1:
        return i

Full solution

class Solution:
    def firstUniqChar(self, s: str) -> int:
        if(len(s) != 0):
              hash_table = {}
              for char in s:
                  if char in hash_table:
                      hash_table[char] = hash_table[char] + 1
                  else:
                      hash_table[char] = 1

              for i, char in enumerate(s):
                  if hash_table[char] == 1:
                      return i

        return -1

Let's submit it and see the result.

Runtime: 208 ms, faster than 22.37% of Python3 online submissions for First Unique Character in a String.
Memory Usage: 13.8 MB, less than 85.20% of Python3 online submissions for First Unique Character in a String.
© 2021, Andrew Losseff