Letter Combinations of a Phone Number

Problem

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

Example 1:

Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]

Example 2:

Input: digits = ""
Output: []

Example 3:

Input: digits = "2"
Output: ["a","b","c"]

Constraints:

  • 0 <= digits.length <= 4
  • digits[i] is a digit in the range [‘2’, ‘9’].

Solution

class Solution {
    public List<String> letterCombinations(String digits) {
        var ans = new ArrayList<String>();
        solve(digits, 0, "", ans);
        return ans;
    }

    public void solve(String digits, int n, String curr, List<String> ans) {
        var m = Map.of(
            '2', List.of("a", "b", "c"),
            '3', List.of("d", "e", "f"),
            '4', List.of("g", "h", "i"),
            '5', List.of("j", "k", "l"),
            '6', List.of("m", "n", "o"),
            '7', List.of("p", "q", "r", "s"),
            '8', List.of("t", "u", "v"),
            '9', List.of("w", "x", "y", "z")
        );

        if (n == digits.length()) {
            if (curr.length() > 0) {
                ans.add(curr);
            }
            return;
        }

        var number = digits.charAt(n);
        var letters = m.get(number);

        for (var l : letters) {
            solve(digits, n + 1, curr + l, ans);
        }
    }
}

Recent posts from blogs that I like

U.S. Soldier Gets 70 Months in Prison for AT&T, Verizon Extortions

A U.S. Army soldier who pleaded guilty to hacking into multiple telecommunications companies and stealing mobile call and text metadata for more than 100 million AT&T customers in 2024 was sentenced to 70 months in federal prison today and ordered to pay nearly $300,000 in restitution to victims.

via Krebs on Security

American in Paris, the brief paintings of Susan Watkins

She started training at the age of 15 in New York, then in Paris, where for a decade she was one of the most successful American painters, but died soon after her return to the USA.

via The Eclectic Light Company

You should all be asking way more questions

When someone is explaining something to me, I ask on average one question every thirty seconds. I’m sure this is frustrating to some people, but it’s actually a good habit and you should do it too.

Trying to understand

Most of the questions I ask are very short, and require very short answers. Typic...

via Sean Goedecke