Coding Problem 2

                Decode number to string
                                                    asked by facebook

Ques. Given any number you have to find the number of ways to decode the number like if you are given the number 12 then it can be decode as "ab" where a=1 and b=2 and "l" where l=12 so the total number of ways to decoed 12 is 2 as "ab" and "l". 

Solution.
We can map our alphabets to the number from 1 to 26. If we have empty string or a single digit number then we can have only one way to decode it but for two or more than 2 digit numbe we have to check each number plus the pair of numbers. Now here we can simplify it as we can have number from 0 to 9 and we have to check only those pair of numbers which are less than 27 as we have 26 alphabets only. 
Suppose we have input as "4" then we can decode it as "d" i.e. only 1 way. If we have empty string (" ") then also we can decode it as 1 way. Now if we have our input starting from 0 then we can not decode it and return 0 because there is no mapped alphabets to digit 0. 
Now think about larger input like "12345". Now we can decode like - 
1 mapped to "a" so "a"+decode("2345") and we can also decode "l"=12 so "l"+decode(345). So now we can write it as - 
num_ways("12345") = num_ways("2345") + num_ways("345"). So we can peform recursion also. Now we can perform recursion and we have two base conditions. In base conditions we have check the null string and string started from 0.
Now let's see the code and clear everything -

def decode(n, k):
        # checking the length 
        if k == 0:
                return 1

        # take the first number of the input string passed to the function and check if it is zero
        s = len(n) - k
        if n[s] == '0':
                return 0

        # take first digit mapped to the character and call function for remaining input string
        result = decode(n, k-1)

        # checking first two digit and calling function for remaining input
        if k >= 2 and int(n[s:s+2]) <= 26:
                result += helper(n, k-2)
        return result

n = input("enter the number: ")
print("No. of ways to decode are {0} ".format(decode(n, len(n))))

Output:  enter the number: 12
                  No. of ways to decode are 2

                  enter the number: 12345
                  No. of ways to decode are 3



Comments

Popular posts from this blog

Coding Problem 10

Coding Problem 3

Coding Problem 9