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


when you have something circular, most of the time you can have one variableand another can be calculated using size, current value and doing %