Why is my code not displaying firstNotRepeatingCharacter in the string, in Python?

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.

>Solution :

Solution:

You should check the character counts after all of the chars have been counted and added to your char_dict.

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
        
        for idx, char in enumerate(s):
            if char_dict.get(char) == 1:
                res.append(char)

        if len(res) == 0:
            return -1
        else:
            return res[0]

Example

Solution().nonrepeating("abacabad")
# 'c'

Leave a Reply