Skip to content

Instantly share code, notes, and snippets.

@optimistiks
Last active May 3, 2023 21:45
Show Gist options
  • Select an option

  • Save optimistiks/f370ff4b17b8157b348b9dc0cd3b2a75 to your computer and use it in GitHub Desktop.

Select an option

Save optimistiks/f370ff4b17b8157b348b9dc0cd3b2a75 to your computer and use it in GitHub Desktop.
Given a string having digits from 1 – 9 inclusive, return all the possible letter combinations that can be made from the numbers in the string. Return the answer in any order.
const lettersMap = {
1: [" "],
2: ["a", "b", "c"],
3: ["d", "e", "f"],
4: ["g", "h", "i"],
5: ["j", "k", "l"],
6: ["m", "n", "o"],
7: ["p", "q", "r", "s"],
8: ["t", "u", "v"],
9: ["w", "x", "y", "z"],
};
function letterCombinationsRec(digits, index, combination, results) {
// base case - combination length equals digit length
// also at this point index points outside of digits, so there are no more digits left to combine
if (combination.length === digits.length) {
results.push(combination.trim());
return;
}
// take letters corresponding to digit at position index
const letters = lettersMap[digits[index]];
// combine each letter with current combination,
// and pass it further incrementing index by 1
// so subsequent recursive calls can combine a new combination with the rest of the digits
for (let i = 0; i < letters.length; ++i) {
letterCombinationsRec(
digits,
index + 1,
`${combination}${letters[i]}`,
results
);
}
}
export function letterCombinations(digits) {
const results = [];
letterCombinationsRec(digits, 0, "", results);
return results;
}

image

// note: the space complexity is different since this solution uses a string instead of array to contain a combination

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment