Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

 

Example 1:

Input: s = "leetcode"
Output: 0

Example 2:

Input: s = "loveleetcode"
Output: 2

Example 3:

Input: s = "aabb"
Output: -1

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of only lowercase English letters.




 from collections import OrderedDict
class Solution:
    def firstUniqChar(self, s: str) -> int:

        hash_map = OrderedDict()
        index = {}

        for i, char in enumerate(s):
            hash_map[char]=hash_map.get(char, 0) + 1
            index[char]=i

        for i, k in enumerate(hash_map.keys()):
            if hash_map[k]==1:
                return index[k]

        return -1

#         hash_map = OrderedDict()

#         for i, char in enumerate(s):
#             hash_map[char]=hash_map.get(char, 0) + 1

#         for i, k in enumerate(hash_map.keys()):
#             if hash_map[k]==1:
#                 return s.find(k)
#         return -1


Random Note


From python 3.7 dict guarantees that order will be kept as they inserted, and popitem will use LIFO order but we need FIFO type system. so we need OrderedDict which have popIten(last = T/F) for this req. One thing, next(iter(dict)) will return the first key of the dict