Letter Combinations of a Phone Number LeetCode solution in Python

1
class Solution:
2
def letterCombinations(self, digits: str) -> List[str]:
3

4
mapping = {
5
"2": "abc",
6
"3": "def",
7
"4": "ghi",
8
"5": "jkl",
9
"6": "mno",
10
"7": "pqrs",
11
"8": "tuv",
12
"9": "wxyz",
13
}
14

15
ans = []
16
first = True
17
for i in range(len(digits)):
18

19
# mult: times we should print each digit
20
mult = 1
21
for j in range(i + 1, len(digits)):
22
mult *= len(mapping[digits[j]])
23

24
# cycles: times we should run same filling cycle
25
if not first:
26
cycles = len(ans) // mult
27
else:
28
cycles = 1
29
if times > 1:
30
cycles //= len(mapping[digits[i]])
31

32
# cyclically adding each digits to answer
33
answer_ind = 0
34
for _ in range(cycles):
35
for char in mapping[digits[i]]:
36
for __ in range(mult):
37
if first:
38
ans.append(char)
39
else:
40
ans[answer_ind] += char
41
answer_ind += 1
42
if first:
43
first = False
44

45
return ans

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0