Skip to content

Crack SDE

Most of the content are generated by AI, with human being reviewed, edited, and revised

Menu
  • Home
  • Daily English Story
  • Tech Interviews
  • Cloud Native
  • DevOps
  • Artificial Intelligence
Menu

Leetcode 17 – Letter Combinations of a Phone Number

Posted on 07/18/202410/18/2024 by user

Description:

Given a string containing digits from 2 to 9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

DigitLetters
2“abc”
3“def”
4“ghi”
5“jkl”
6“mno”
7“pqrs”
8“tuv”
9“wxyz”

Example 1:

Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]

Example 2:

Input: digits = ""
Output: []

Example 3:

Input: digits = "2"
Output: ["a","b","c"]

Analysis:

This problem is essentially generating all possible combinations from the digit-to-letter mappings. Each digit can be mapped to 3-4 possible letters, and the goal is to generate all possible combinations using the provided digits.

To solve this problem, a recursive backtracking approach can be used. Starting from the first digit, we explore all possible letter choices, and then proceed to the next digit, combining the choices until we have generated all combinations.

Python Code:

def letterCombinations(digits: str):
    # Mapping of digits to corresponding letters
    phone_map = {
        '2': 'abc',
        '3': 'def',
        '4': 'ghi',
        '5': 'jkl',
        '6': 'mno',
        '7': 'pqrs',
        '8': 'tuv',
        '9': 'wxyz'
    }

    # If the input is empty, return an empty list
    if not digits:
        return []

    # List to store the result combinations
    result = []

    # Backtracking function to generate combinations
    def backtrack(index, current_combination):
        # If the current combination is as long as the digits, add it to the results
        if index == len(digits):
            result.append(current_combination)
            return

        # Get the letters corresponding to the current digit
        current_digit = digits[index]
        letters = phone_map[current_digit]

        # Recursively generate all combinations
        for letter in letters:
            backtrack(index + 1, current_combination + letter)

    # Start the backtracking with an empty combination
    backtrack(0, "")

    return result

Example usage:

print(letterCombinations("23"))
# Output: ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']

Time Complexity:

The time complexity of the solution is O(3^n × 4^m), where:

  • n is the number of digits that map to 3 letters (2, 3, 4, 5, 6, 8).
  • m is the number of digits that map to 4 letters (7, 9).

In the worst case, if all the digits map to 4 letters (like ‘7’ and ‘9’), there would be 4^m combinations to explore. However, since most digits map to 3 letters, the complexity varies based on the actual input. Therefore, a loose upper bound is O(4^n) where n is the length of the digits string.

Space Complexity:

  • The space complexity is O(n) for storing the recursion stack, where n is the length of the input digits.
  • Additionally, the space required to store the result list is O(4^n), where n is the length of the digits, as each combination is stored in the result.

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Related

Recent Posts

  • LC#622 Design Circular Queue
  • Started with OpenTelemetry in Go
  • How Prometheus scrap works, and how to find the target node and get the metrics files
  • How to collect metrics of container, pods, node and cluster in k8s?
  • LC#200 island problem

Recent Comments

  1. another user on A Journey of Resilience

Archives

  • May 2025
  • April 2025
  • February 2025
  • July 2024
  • April 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • June 2023
  • May 2023

Categories

  • Artificial Intelligence
  • Cloud Computing
  • Cloud Native
  • Daily English Story
  • Database
  • DevOps
  • Golang
  • Java
  • Leetcode
  • Startups
  • Tech Interviews
©2025 Crack SDE | Design: Newspaperly WordPress Theme
Manage Cookie Consent
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
View preferences
{title} {title} {title}