Letter Combinations of a Phone Number LeetCode solution in Python
1class Solution:2def letterCombinations(self, digits: str) -> List[str]:34mapping = {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}1415ans = []16first = True17for i in range(len(digits)):1819# mult: times we should print each digit20mult = 121for j in range(i + 1, len(digits)):22mult *= len(mapping[digits[j]])2324# cycles: times we should run same filling cycle25if not first:26cycles = len(ans) // mult27else:28cycles = 129if times > 1:30cycles //= len(mapping[digits[i]])3132# cyclically adding each digits to answer33answer_ind = 034for _ in range(cycles):35for char in mapping[digits[i]]:36for __ in range(mult):37if first:38ans.append(char)39else:40ans[answer_ind] += char41answer_ind += 142if first:43first = False4445return ans