# Letter Combinations of a Phone Number

`Backtracking`

Medium

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 (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

Example:

``````Input:
"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.

## Analysis

The phone digits to letters mapping:

``````String[] KEYS = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }
``````

## Solution

#### Recursive

Time complexity : O(3^N × 4^M ) where N is the number of digits in the input that maps to 3 letters (e.g. 2, 3, 4, 5, 6, 8) and M is the number of digits in the input that maps to 4 letters (e.g. 7, 9), and N+M is the total number digits in the input.

Space complexity : O(3^N × 4^M ) since one has to keep 3^N times 4^M solutions.

https://leetcode.com/problems/letter-combinations-of-a-phone-number/solution/

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

public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if (digits.length() == 0) {
return res;
}

helper(digits, 0, "", res);

return res;
}

private void helper(String digits, int index, String path, List<String> res) {
if (index == digits.length()) {
return;
}
String letters = KEYS[digits.charAt(index) - '0'];
for (char c : letters.toCharArray()) {
helper(digits, index + 1, path + c, res);
}
}
}
``````

#### Queue, BFS

``````class Solution {
public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) {
return queue;
}
char[] digitChar = digits.toCharArray();

String[] phone = new String[] {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
queue.offer("");
for (int i = 0; i < digitChar.length; i++) {
char[] letters = phone[digitChar[i] - '0'].toCharArray();

while  (queue.peek().length() == i) {
String str = queue.poll();
for (char c : letters) {
queue.offer(str + c);
}
}
}
return queue;
}
}
``````