Letter Combinations of a Phone Number — LeetCode 17 Python Solution
- Problem
- #17
- Pattern
- Backtracking
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- digits = "23"
- Output
- ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Python solution
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return []
d = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
ans = [""]
for i in digits:
s = d[int(i) - 2]
ans = [a + b for a in ans for b in s]
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(4^n) |
| Space | O(4^n) auxiliary |
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 17. Letter Combinations of a Phone Number is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.
The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.
Related problems
On study lists
This problem is on NeetCode 150, Grind 75, LeetCode 75 and Top Interview 150.
Frequently asked questions
- How hard is LeetCode 17. Letter Combinations of a Phone Number?
- LeetCode 17. Letter Combinations of a Phone Number is rated Medium on LeetCode.
- What is the time complexity of LeetCode 17. Letter Combinations of a Phone Number?
- The Python solution on this page runs in O(4^n).
- What is the space complexity of LeetCode 17. Letter Combinations of a Phone Number?
- The Python solution on this page uses O(4^n) auxiliary space.
- What topics does LeetCode 17. Letter Combinations of a Phone Number cover?
- LeetCode 17. Letter Combinations of a Phone Number is tagged Hash Table, String and Backtracking on LeetCode.