Skip to content

17. Letter Combinations of a Phone Number

Medium LeetCode

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.

Example 1

17. Letter Combinations of a Phone Number

Input: digits = "23"

Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]

Explanation: The digit "2" maps to "abc" and "3" maps to "def". All possible combinations are formed by taking one letter from each digit.

Example 2

Input: digits = ""

Output: []

Explanation: Since there are no digits, there are no letter combinations possible.

Example 3

Input: digits = "2"

Output: ["a","b","c"]

Explanation: The digit "2" maps to "abc", so the possible combinations are "a", "b", and "c".

Constraints

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

How to solve the problem

  • Backtracking (DFS)
python
class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits:
            return []
        result = []
        phone_map = { "2": "abc", "3": "def", "4": "ghi", "5": "jkl",
            "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"}
        def backtracking(index, path: str):
            if index == len(digits):
                result.append(path)
                return
            possible_letter = phone_map[digits[index]]
            for letter in possible_letter:
                 backtracking(index + 1, path + letter)
        backtracking(0, "")
        return result

Complexity

  • Time complexity: O(K*C(n, k))
  • Space complexity: O(K*C(n, k))

Comments

No comments yet. Be the first to comment!