First Unique Character in a String in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string and we have to find the first unique character in the string. So if the string is like “people”, the first letter whose occurrence is one is ‘o’. So the index will be returned, that is 2 here. If there is no such character, then return -1.

To solve this, we will follow these steps −

  • create one frequency map
  • for each character c in the string, do
    • if c is not in frequency, then insert it into frequency, and put value 1
    • otherwise, increase the count in frequency
  • Scan the frequency map, if the value of a specific key is 1, then return that key, otherwise return -1

Example

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def firstUniqChar(self, s):
      """
      :type s: str
      :rtype: int
      """
      frequency = {}
      for i in s:
         if i not in frequency:
            frequency[i] = 1
         else:
            frequency[i] +=1
      for i in range(len(s)):
         if frequency[s[i]] == 1:
            return i
      return -1
ob1 = Solution()
print(ob1.firstUniqChar("people"))
print(ob1.firstUniqChar("abaabba"))

Input

"people"
"abaabba"

Output

2
-1
raja
Published on 09-Jan-2020 09:28:20
Advertisements