GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — coding-problems/Other/letter_combinations.py at master · developertyrone/coding-problems

Expand file tree

/

letter_combinations.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
56 lines (44 loc) · 1.77 KB
/

letter_combinations.py

Copy path

File metadata and controls

56 lines (44 loc) · 1.77 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
'''
Letter Combinations of a Phone Number
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters is just like on the telephone buttons. Note that 1 does not map to any letters.
Input: '23'
Output: ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']
=========================================
This problem could be solved in several ways (using recursion, stack, queue...) and the complexity is same in all, but this one has the simplest code.
Iterate all digits and in each step look for the previous combinations, create a new 3 or 4 combinations from each combination using the mapping letters.
Time Complexity: O(3^N * 4^M) , N = number of digits that maps to 3 letters, M = number of digits that maps to 4 letters
Space Complexity: O(3^N * 4^M)
'''
############
# Solution #
############
def letter_combinations(digits):
if len(digits) == 0:
return []
mappings = {
'2': ['a','b','c'],
'3': ['d','e','f'],
'4': ['g','h','i'],
'5': ['j','k','l'],
'6': ['m','n','o'],
'7': ['p','q','r','s'],
'8': ['t','u','v'],
'9': ['w','x','y','z']
}
prev_combinations = ['']
for digit in digits:
new_combinations = []
for combination in prev_combinations:
# use the mappings and create new combinations
for mapping in mappings[digit]:
new_combinations.append(combination + mapping)
# save the newest combinations
prev_combinations = new_combinations
return prev_combinations
###########
# Testing #
###########
# Test 1
# Correct result => ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']
print(letter_combinations('23'))
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.