Skip to content

Instantly share code, notes, and snippets.

@codertcet111
Created March 29, 2024 14:57
Show Gist options
  • Save codertcet111/b758af6a174764b56c54936c7f0be3db to your computer and use it in GitHub Desktop.
Save codertcet111/b758af6a174764b56c54936c7f0be3db to your computer and use it in GitHub Desktop.
Leetcode 17 problem
Leetcode : 17 Letter combination of phone number
# @param {String} digits
# @return {String[]}
def letter_combinations(digits)
return [] if digits.length == 0
hash_phone = {
'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']
}
# Next line: split and replace digits by its respective array
rep_str_a = digits.split("").map {|d| hash_phone[:"#{d}"]}
it_arr = rep_str_a[0]
# Next if only one digit return single array
return it_arr if rep_str_a.length == 1
# Iterate and get product of each
(1..rep_str_a.length - 1).each do |ind|
it_arr = it_arr.product(rep_str_a[ind])
end
it_arr.map{|x| x.join('')}
# rep_str_a.combination(digits.length).to_a
end
#puts letter_combinations('23')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment