Suppose we have a stream of characters, or we can consider a string and we have to find the first non-repeating 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 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 specific key is 1, then return that key, otherwise return -1
Example
Let us see the following implementation to get better understanding −
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