Program to find all possible strings typed using phone keypad in python

Suppose we have a string containing digits from 2-9. We have to find all possible letter combinations that the number could generate. One mapping of digit to letters (just like on the telephone buttons) is given below ?

1 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
* 0 #

For example, if the given string is "49", then the possible strings will be ['gw', 'gx', 'gy', 'gz', 'hw', 'hx', 'hy', 'hz', 'iw', 'ix', 'iy', 'iz']

Algorithm

To solve this problem, we will use backtracking approach with these steps ?

  • Create a mapping of digits to their corresponding letters
  • Use a recursive function that builds combinations character by character
  • For each digit, try all possible letters and recursively build the rest
  • When we've processed all digits, add the current combination to results

Using Backtracking Approach

class Solution:
    def letterCombinations(self, digits):
        if len(digits) == 0:
            return []
        
        # Mapping digits to letters
        phone_map = {
            '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
            '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'
        }
        
        result = []
        self.backtrack(digits, phone_map, result, "", 0)
        return result
    
    def backtrack(self, digits, phone_map, result, current_string, current_level):
        # Base case: if we've processed all digits
        if current_level == len(digits):
            result.append(current_string)
            return
        
        # Get current digit and its corresponding letters
        current_digit = digits[current_level]
        letters = phone_map[current_digit]
        
        # Try each letter for current digit
        for letter in letters:
            self.backtrack(digits, phone_map, result, 
                         current_string + letter, current_level + 1)

# Test the solution
solution = Solution()
print(solution.letterCombinations("49"))
['gw', 'gx', 'gy', 'gz', 'hw', 'hx', 'hy', 'hz', 'iw', 'ix', 'iy', 'iz']

Using itertools.product()

Python's itertools.product() provides a simpler approach for generating all combinations ?

import itertools

def letter_combinations_itertools(digits):
    if not digits:
        return []
    
    phone_map = {
        '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
        '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'
    }
    
    # Get letters for each digit
    letter_groups = [phone_map[digit] for digit in digits]
    
    # Generate all combinations and join them
    combinations = itertools.product(*letter_groups)
    return [''.join(combo) for combo in combinations]

# Test the solution
print(letter_combinations_itertools("23"))
['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']

Comparison

Approach Time Complexity Space Complexity Readability
Backtracking O(4^n) O(4^n) More verbose
itertools.product() O(4^n) O(4^n) Concise

Conclusion

Both approaches generate all possible letter combinations from phone keypad digits. The backtracking method provides better understanding of the recursive process, while itertools.product() offers a more concise solution for practical use.

Updated on: 2026-03-25T12:52:22+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements