Join DevzConnect — where devs connect, code, and level up together. Got questions? Stuck on a bug? Or just wanna help others crush it? Jump in and be part of a community that gets it
Welcome back to DevzConnect — where devs connect, code, and level up together. Ready to pick up where you left off? Dive back in, ask questions, share wins, or help others crush their goals!
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Letter Combinations of a Phone Number – Leet code – medium
function letterCombinations(digits) { if (!digits) return []; const phoneMap = { "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz" }; const result = []; const backtrack = (index, path) => { if (path.length === digits.length) { result.push(path.join('Read more
Explanation:
Base Case:
If
digits
is empty, return an empty array.phoneMap
:Maps each digit (2-9) to its corresponding letters.
Backtracking (
backtrack
):index
: Tracks the current position in thedigits
string.path
: Holds the current combination as an array of characters.path.length
equalsdigits.length
, it forms a valid combination and is pushed toresult
.Output:
["ad","ae","af","bd","be","bf","cd","ce","cf"]
[]
["a","b","c"]
This solution uses DFS (Depth-First Search) with backtracking and has a time complexity of O(4^n), where n is the length of
See lessdigits
(since some digits map to up to 4 letters, e.g., ‘7’ and ‘9’).