# Letter Combinations of a Phone LeetCode Solution | Easy Approach

Share:

Letter Combinations of a Phone | Given a string containing digits from `2-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.

Example 1:

```Input: digits = "23"
```

Example 2:

```Input: digits = ""
Output: []
```

Example 3:

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

Constraints:

• `0 <= digits.length <= 4`
• `digits[i]` is a digit in the range `['2', '9']`.

Time: O(n4n)
Space: O(4n)

### C++

``````class Solution {
public:
vector<string> letterCombinations(string digits) {
if (digits.empty())
return {};

vector<string> ans{""};
const vector<string> digitToLetters{"",    "",    "abc",  "def", "ghi",
"jkl", "mno", "pqrs", "tuv", "wxyz"};

for (const char d : digits) {
vector<string> temp;
for (const string& s : ans)
for (const char c : digitToLetters[d - '0'])
temp.push_back(s + c);
ans = move(temp);
}

return ans;
}
};
``````

### Java

``````class Solution {
public List<String> letterCombinations(String digits) {
if (digits.isEmpty())
return new ArrayList<>();

List<String> ans = new ArrayList<>();
final String[] digitToLetters = {"",    "",    "abc",  "def", "ghi",
"jkl", "mno", "pqrs", "tuv", "wxyz"};

for (final char d : digits.toCharArray()) {
List<String> temp = new ArrayList<>();
for (final String s : ans)
for (final char c : digitToLetters[d - '0'].toCharArray())
ans = temp;
}

return ans;
}
}

``````

### Python

``````class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return []

ans = ['']
digitToLetters = ['', '', 'abc', 'def', 'ghi',
'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']

for d in digits:
temp = []
for s in ans:
for c in digitToLetters[ord(d) - ord('0')]:
temp.append(s + c)
ans = temp

return ans

``````

#### Watch Tutorial

Checkout more Solutions here