Letter Combinations of a Phone Number
Letter Combinations of a Phone Number
Given a digit string (2-9), return all possible letter combinations based on telephone keypad mapping. Order does not matter.
Function signature
func LetterCombinations(digits string) []string
Inputs / outputs
digits: string of digits 2-9.- Return: all possible letter combinations.
Example
digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Constraints
- 0 <= len(digits) <= 4
Core idea (near-solution)
This is a Cartesian product over digit-to-letter mappings. Use backtracking to build one character at a time.
Invariant: the current path has length i and matches the first i digits.
Algorithm (step-by-step)
- If
digitsis empty, return empty slice. - Map digits to letter strings ("2" -> "abc", etc.).
- DFS with index
iand bufferpath:- If
i == len(digits), record the string. - For each letter in mapping[digits[i]], append and recurse.
- If
- Return the results.
Correctness sketch
- Invariant: the current path has length
iand matches the firstidigits. - Each recursive step extends a valid partial solution.
- Backtracking explores all possible choices without duplication.
- Thus every valid solution is found and recorded.
Trace (hand walkthrough)
Trace Walkthrough
Example input:
digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Walk:
- digits "2" -> [a,b,c]
- extend with "3" (d,e,f) -> ad, ae, af, bd, be, bf, cd, ce, cf
Pitfalls to avoid
- Returning
[]string{""}for empty input (should be empty). - Using rune-based iteration incorrectly (letters are ASCII here).
Complexity
- Time:
O(3^n)toO(4^n)depending on digits. - Extra space:
O(n)recursion depth (excluding output).
Implementation notes (Go)
- Use a
[]bytebuffer for the current path and convert to string on output.
Run tests to see results
No issues detected