Leetcode Letter Combinations of a Phone Number problem solution in Python programming

In the Leetcode Letter Combinations of a Phone Number problem solution in Python programming Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

Leetcode Letter Combinations of a Phone Number problem solution in Python programming

charLookup = {
    '2': 'abc',
    '3': 'def',
    '4': 'ghi',
    '5': 'jkl',
    '6': 'mno',
    '7': 'pqrs',
    '8': 'tuv',
    '9': 'wxyz'
}


class Solution(object):
    def letterCombinations(self, digits):
        if not digits:
            return []
        theseChars = charLookup[digits[0]]        
        nextCombinations = self.letterCombinations(digits[1:])
        result = []
        for s in theseChars:
            if nextCombinations:
                result.extend([s+f for f in nextCombinations])
            else:
                result.append(s)                
        return result

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *