TC O(n) + SC O(n)

  • 0
    class Solution(object):
        def firstUniqChar(self, s):
            :type s: str
            :rtype: int
            #Char: first index we saw
            h = {}
            #Index of non-repeating
            non_repeating_char = [None] * len(s)
            # if char doesn't exist in h
            # we'll add its index in h, and
            # Set True for current char index in non_repating_char
            #but if it exists we'll find the first index from h
            #and set it to None in non_repeating_char
            #At the end if non_repeating_char is all None then return -1
            #else return first index which has set True
            for i in range(len(s)):
                if s[i] not in h:
                    h[s[i]] = i
                    #probably non_repeating_char
                    non_repeating_char[i] = True
                    non_repeating_char[h[s[i]]] = None
            #Find the first index which has True
            for i in range(len(s)):
                if non_repeating_char[i]:
                    return i
            return -1

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.