Ecommet

Letter Combinations of a Phone Number

Medium Problem 90 of 151 Java and Python

Problem

Given a string of digits from 2 to 9, return all letter combinations the number could represent on a phone keypad (2 → abc, 3 → def, 4 → ghi, 5 → jkl, 6 → mno, 7 → pqrs, 8 → tuv, 9 → wxyz). Return them in any order.

An empty input gives an empty list.

Example 1

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

Example 2

Input
digits = ""
Output
[]

Constraints

  • 0 ≤ digits.length ≤ 4
  • digits[i] is between 2 and 9.

Explanation

Each digit adds one letter, chosen from 3 or 4 options. Every string is one path through these choices: a textbook backtracking tree whose depth is the number of digits.

Approach 1 · Better

Build level by level

  • Time O(4ⁿ · n)
  • Space O(4ⁿ · n)

Start from [""]. For each digit, append each of its letters to every string built so far.

  1. If digits is empty, return [].
  2. result = [""]; for each digit, result = [s + letter for s in result for letter in keys[digit]].
Java
import java.util.*;

class Solution {
    private static final String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };

    public List<String> letterCombinations(String digits) {
        if (digits.isEmpty()) {
            return new ArrayList<>();
        }
        List<String> result = new ArrayList<>();
        result.add("");
        for (char digit : digits.toCharArray()) {
            List<String> next = new ArrayList<>();
            for (String prefix : result) {
                for (char letter : KEYS[digit - '0'].toCharArray()) {
                    next.add(prefix + letter);
                }
            }
            result = next;
        }
        return result;
    }
}
Python
class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        keys = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl",
                "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"}
        if not digits:
            return []
        result = [""]
        for digit in digits:
            result = [prefix + letter for prefix in result for letter in keys[digit]]
        return result

Approach 2 · Optimal

Backtracking

  • Time O(4ⁿ · n)
  • Space O(n) recursion besides the output

Recursively choose a letter for each digit, using one shared buffer and undoing each choice.

  1. backtrack(i): if i == digits.length, record the buffer.
  2. For each letter of digits[i]: append, recurse with i + 1, remove.
Java
import java.util.*;

class Solution {
    private static final String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };

    public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<>();
        if (!digits.isEmpty()) {
            backtrack(digits, 0, new StringBuilder(), result);
        }
        return result;
    }

    private void backtrack(String digits, int i, StringBuilder path, List<String> result) {
        if (i == digits.length()) {
            result.add(path.toString());
            return;
        }
        for (char letter : KEYS[digits.charAt(i) - '0'].toCharArray()) {
            path.append(letter);
            backtrack(digits, i + 1, path, result);
            path.deleteCharAt(path.length() - 1);
        }
    }
}
Python
class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        keys = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl",
                "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"}
        result, path = [], []

        def backtrack(i):
            if i == len(digits):
                result.append("".join(path))
                return
            for letter in keys[digits[i]]:
                path.append(letter)
                backtrack(i + 1)
                path.pop()

        if digits:
            backtrack(0)
        return result

Complexity compared

ApproachTimeSpace
Better Build level by levelO(4ⁿ · n)O(4ⁿ · n)
Optimal BacktrackingO(4ⁿ · n)O(n) recursion besides the output

Key takeaways

  • Remember the empty input: it must return [], not [""].

Your notes

Saved in this browser as you type.

Solved it on your own?

Mark it done to track your progress, or star it to come back before an interview.

Next problem