17 Letter Combinations of a Phone Number

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

Input:
Digit string "23"

Output:
 ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note: Although the above answer is in lexicographical order, your answer could be in any order you want.

The Idea: First map each digit to its cooresponding alphabet. Begin with the characters to the first digit.

Next, recursively build upon this string by copying each s[i] and appending each character cooresponding to the next digit.

Complexity: O(4^n) time and O(4^n) space

Python Solution 1

This is actually a more efficient solution because I rather than completely rewriting over prev in the previous implementation, I pass in the updated seed (which is next), and return it in the end.

Python Solution 2

Incrementally build off the base case, and just keep adding to it.

Last updated

Was this helpful?