Coding Problem 8

              First Recurring Character

                                                       asked by Google


Ques. From a given string return the first recurring character of the string. For example - if string is "ABCDBA" then return B and if string is "ABCD" then return None because no character is recurring.


Solution.

The first solution that come to our mind is that while traversing each character of string keep track of already occured character and if any character occured again then return that character. So to keep track of characters we can use dictionary or list. Lets see this - 

def first_rec_char(s):

    char_list = []

    for i in s:

        if i in char_list:

            return i

        else:

            char_list.append(i)

    return None


This method will work but if we see clearly then we find that time complexity is somewhat O(n^2) becuase we are searching the current element in the list of elements. If we use dictionary then also we will speen the time in searching the elements.

Well here is another solution. We will create a large array in which each index value will corresponds to the ASCII value of character. Initially every index value will be 0. Now for every character we traverse we will increase the index value which corresponds the ASCII value of character and we will check the value of that index if value becomes greater than 1 then we know that we have already traversed that character and we can return that otherwise continue till the last character of string. To get the ASCII value we will use ord() function. Lets see this code too - 


def first_rec_char(s):

temp = [0]*128

for i in s:

temp[ord(i)] += 1

if temp[ord(i)] > 1:

return i

return None

print(first_rec_char("ABCDBA"))


Output : B

Comments

Popular posts from this blog

Coding Problem 10

Coding Problem 3

Coding Problem 9