So, I am solving this code signal problem and it's problem statement is as follows
Given a string s consisting of small English letters, find and return the first instance of a non-repeating character in it.
So, I have saved the characters inside a dictionary along with their frequency of occurances and the characters that occur only one are added to empty array. And then I have returned the first occurances that appear only once. But I am not able to get hte output. Following is my code.
class Solution(object):
def nonrepeating(self, s):
char_dict = {}
res = []
for idx, char in enumerate(s):
countChar = 1 + char_dict.get(char, 0)
char_dict[char] = countChar
if countChar == 1:
res.append(char)
if len(res) == 0:
return -1
else:
return res[0]
For input s="abacabad" , it should give 'c' as the answer but it's giving 'a'
I have created a dictionary to store the characters and their occurances ,and then I have created an empty array to store the characters that occur only once so i can written the first index element.
collections.Counter()
that does the counting for you.