Daily Coding Problem: Problem #81
Good morning! Here's your coding interview problem for today.
This problem was asked by Yelp.
Given a mapping of digits to letters (as in a phone number), and a digit string, return all possible letters the number could represent. You can assume each valid number in the mapping is a single digit.
For example if {“2”: [“a”, “b”, “c”], 3: [“d”, “e”, “f”], …} then “23” should return [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf"].
- assuming there isn't a 1 or 0 because those have no mappings on my phone
- assuming the strict character set of 2-9 as an input (no alphas, no special characters)
if input is empty, return empty string
if the input is a single digit, return the mapping[single digit]
if '23', we need to perform 2 loops, because the length of '23' is two
input = '23'
input.split('') //['2','3']
const results = [] //here we keep the results
input.forEach((el, index) => ) if it's the first index, we push all the el arrays into the result
if there are more to process, we loop through each result and append the el array's character
finally, we sort the result array
const input = '234'
console.log('answer', possibles(input))
function possibles(input) {
const mapping = {
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"]
}
if (!input) return "nothing" //no input
if (input.length == 1) return mapping[input] //single input
const inputArray = input.toString().split('')
let results = []
inputArray.forEach((el, index) => { //['2', '3']
if (index == 0) {
results = results.concat(mapping[el]) //['a','b','c']
} else {
//for each el, we replace that el with el + every combination of mapping[el]
let temp = []
results.forEach(resultEl => {
mapping[el].forEach(mappingEl => {
temp.push(resultEl + mappingEl)
})
})
results = temp
}
})
return results
}
I try to solved this case with another language. I use VB.net for coding.