Overview
Given a string containing digits 2-9, return all possible letter combinations the number could represent (phone keypad mapping). Return in any order.
Mapping: 2→abc, 3→def, 4→ghi, 5→jkl, 6→mno, 7→pqrs, 8→tuv, 9→wxyz
Constraints
0 <= digits.length <= 4digits[i]is between '2' and '9'.
Examples
letterCombinations("23");
// => ["ad","ae","af","bd","be","bf","cd","ce","cf"]
letterCombinations("");
// => []Solution
Reveal solution
function letterCombinations(digits) {
if (!digits.length) return [];
const map = { '2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz' };
const result = [];
function backtrack(i, path) {
if (i === digits.length) { result.push(path); return; }
for (const c of map[digits[i]]) backtrack(i + 1, path + c);
}
backtrack(0, "");
return result;
}Resources
letter-combinations-phone-number.js
Letter Combinations of a Phone Number
mediumcodingAlgorithmsBacktracking
Overview
Given a string containing digits 2-9, return all possible letter combinations the number could represent (phone keypad mapping). Return in any order.
Mapping: 2→abc, 3→def, 4→ghi, 5→jkl, 6→mno, 7→pqrs, 8→tuv, 9→wxyz
Constraints
0 <= digits.length <= 4digits[i]is between '2' and '9'.
Examples
letterCombinations("23");
// => ["ad","ae","af","bd","be","bf","cd","ce","cf"]
letterCombinations("");
// => []Solution
Reveal solution
function letterCombinations(digits) {
if (!digits.length) return [];
const map = { '2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz' };
const result = [];
function backtrack(i, path) {
if (i === digits.length) { result.push(path); return; }
for (const c of map[digits[i]]) backtrack(i + 1, path + c);
}
backtrack(0, "");
return result;
}Resources
NameTopicDifficulty
103 of 103 problems