// note: the space complexity is different since this solution uses a string instead of array to contain a combination
Last active
May 3, 2023 21:45
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
