Skip to content

Commit 9447151

Browse files
author
sambabib
committed
js solution to _17
1 parent 30ac3db commit 9447151

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Diff for: javascript/_17.js

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
function letterCombinations(digits) {
2+
// If the input is an empty string, return an empty array.
3+
if (digits.length === 0) {
4+
return [];
5+
}
6+
7+
// Mapping of digits to letters as per the telephone keypad using a javascript dictionary.
8+
const digitToChar = {
9+
'2': ['a', 'b', 'c'],
10+
'3': ['d', 'e', 'f'],
11+
'4': ['g', 'h', 'i'],
12+
'5': ['j', 'k', 'l'],
13+
'6': ['m', 'n', 'o'],
14+
'7': ['p', 'q', 'r', 's'],
15+
'8': ['t', 'u', 'v'],
16+
'9': ['w', 'x', 'y', 'z']
17+
};
18+
19+
// Resultant array to store all possible combinations
20+
const result = [];
21+
22+
// Backtracking function to generate combinations
23+
function backtrack(index, currentCombination) {
24+
// if the current combination has the same length as the input digits.
25+
if (index === digits.length) {
26+
result.push(currentCombination);
27+
return;
28+
}
29+
30+
// Get the letters that the current digit maps to.
31+
let letters = digitToChar[digits[index]];
32+
33+
// Loop through the letters and call backtrack recursively for the next digit.
34+
for (let letter of letters) {
35+
backtrack(index + 1, currentCombination + letter);
36+
}
37+
}
38+
39+
// Start backtracking from the first digit (index 0) with an empty string as the initial combination.
40+
backtrack(0, '');
41+
42+
return result;
43+
};

0 commit comments

Comments
 (0)