Skip to content

Commit 0e3da69

Browse files
author
Jacob Shulenberger
committed
Add letter combinations of a phone number algorithm
1 parent e659933 commit 0e3da69

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* @param {string} digits
3+
* @return {string[]}
4+
*/
5+
var letterCombinations = function(digits) {
6+
let sanitizeInput = function(unsanitizedDigits) {
7+
let regex = /(\W|_|[0-1a-zA-Z])/g;
8+
let sanitized = unsanitizedDigits.replace(regex, "");
9+
return sanitized;
10+
};
11+
const mapping = {
12+
2: ["a", "b", "c"],
13+
3: ["d", "e", "f"],
14+
4: ["g", "h", "i"],
15+
5: ["j", "k", "l"],
16+
6: ["m", "k", "o"],
17+
7: ["p", "q", "r", "s"],
18+
8: ["t", "u", "v"],
19+
9: ["w", "x", "y", "z"],
20+
};
21+
let sanitizedDigits = sanitizeInput(digits);
22+
if (sanitizedDigits.length > 12) {
23+
return "1,388,674 combinations should be more than enough for you. Provide 12 or fewer digits.";
24+
}
25+
if (sanitizedDigits.length < 1) {
26+
return "Nothing to return.";
27+
}
28+
let finalArray = [];
29+
30+
const backtrackRecursive = function(combination, nextDigits) {
31+
if (nextDigits.length === 0) {
32+
finalArray.push(combination);
33+
} else {
34+
for (let i = 0; i < mapping[nextDigits[0]].length; i += 1) {
35+
backtrackRecursive(
36+
combination + mapping[nextDigits[0]][i],
37+
nextDigits.slice(1)
38+
);
39+
}
40+
}
41+
};
42+
43+
if (sanitizedDigits) {
44+
backtrackRecursive("", sanitizedDigits);
45+
}
46+
47+
return finalArray;
48+
};

0 commit comments

Comments
 (0)