Leetcode - Letter Combinations of a Phone Number Solution
1 min read

Leetcode - Letter Combinations of a Phone Number Solution

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 digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

Example 1:

Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]

Example 2:

Input: digits = ""
Output: []

Example 3:

Input: digits = "2"
Output: ["a","b","c"]


  • 0 <= digits.length <= 4
  • digits[i] is a digit in the range ['2', '9'].

Solution in Python

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        def helper(digits):
            hash_map = {"1":"", "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8":"tuv", "9":"wxyz"}
            digits = dict(enumerate(digits))
            a = hash_map[digits.get(0, "1")]
            b = hash_map[digits.get(1, "1")]
            c = hash_map[digits.get(2, "1")]
            d = hash_map[digits.get(3, "1")]
            for i in a:
                if len(digits)==1:
                    yield "".join([i])
                for j in b:
                    if len(digits)==2:
                        yield "".join([i,j])
                    for k in c:
                        if len(digits)==3:
                            yield "".join([i,j,k])
                        for l in d:
                            yield "".join([i,j,k,l])
        return list(helper(digits))

Enjoying these posts? Subscribe for more

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.