Leetcode: First Unique Character

Rachit Gupta
1 min readDec 25, 2016

--

To find the first character in a given string we need to take the following steps.

  1. Create a dictionary to store indices of each character
  2. Check if character was already seen and change its index in the dictionary to length of the input. In this way all repeated characters will have length of input as their value in the dictionary
  3. So only the characters with one occurrence will have a valid index in the dictionary
  4. Take the minimum of these values to get the first unique character
  5. If there was no unique character then we will get length of input as result

Remarks:

  1. O(n) time complexity, for iterating the array, note that lookup in dictionary takes O(1) time
  2. O(n) space complexity for storing the characters in the dictionary
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
d, l = {}, len(s)
for i, c in enumerate(s):
d[c] = l if c in d else i
res = min(d.values()) if d else -1
return res if res < l else -1

--

--