1

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.

1
  • FYI there's a built-in collections.Counter() that does the counting for you.
    – Barmar
    Commented Sep 12, 2023 at 16:31

1 Answer 1

0

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'
3
  • 1
    Ahh, so I was missng that thing. I was actually thinking, it's counting automatcally, I had visualise, how I want to do. Thank you so much :)
    – vilnius19
    Commented Sep 12, 2023 at 16:39
  • 1
    "bcccccccb" has no non-repeating characters. When I run that, I get -1 back, which is correct. Am I missing something else? Commented Sep 12, 2023 at 16:47
  • 1
    It's passing that test now, I just had to put return '_' instead of return -1 as that's what was specified in the problem :)
    – vilnius19
    Commented Sep 13, 2023 at 9:17

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.