Skip to main content

Solution 7: Keypad Combinations

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent if typed sequentially on a telephone keypad. For the purpose of this exercise, a mapping of numbers to the possible letters they could represent is given. Return an array with all possible combinations in any order. Given an empty string, return an empty array.

def letter_combinations(digits)
keypad = {
'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']
}

digits = digits.split('')
possible_letterings = digits.map { |d| keypad[d] }

return [] if possible_letterings.length < 1

combinations = possible_letterings.slice(1..).reduce(possible_letterings[0]) do |result, letters|
result.product(letters)
end

combinations.map do |product|
product.class == Array ? product.join : product
end
end