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"]

Constraints:

  • 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))

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe