Imagine an old-school mobile keypad where letters are mapped to digits (e.g., '2' maps to "abc", '7' maps to "pqrs"). A user types a sequence of digits. You need to find the total number of possible text messages that could have been sent. For instance, "22" could be "aa" (pressed 2 once, twice) or "b" (pressed 2 twice). Return the answer modulo .
This problem is asked by companies like Microsoft and Goldman Sachs to test your understanding of Dynamic Programming on strings. It’s a variation of the "Climbing Stairs" or "Ways to Decode" problem. It evaluations your ability to handle variable jump lengths (some keys have 3 letters, some have 4) and aggregate results across a sequence.
This is a 1D Dynamic Programming problem.
dp[i] as the number of ways to decode the prefix of the string of length i.i, look at the previous characters. If they are the same as the current character, you can form a "group".dp[i] = sum(dp[i-k]) for all valid group lengths k.String: "222" (Key 2 has 3 letters: a, b, c)
dp[0] = 1 (empty string)dp[1] = dp[0] = 1 (message: "a")dp[2] = dp[1] + dp[0] = 2 (messages: "aa", "b")dp[3] = dp[2] + dp[1] + dp[0] = 2 + 1 + 1 = 4 (messages: "aaa", "ab", "ba", "c")
Total: 4.A common error is not distinguishing between keys that have 3 letters and those that have 4 ('7' and '9'). Another mistake is not applying the modulo at each addition, leading to overflow. Some candidates also forget to check if the sequence of characters is actually identical before summing the previous DP states.
This problem is a great way to practice the "look-back" DP technique. When the number of ways to reach a state depends on a small, fixed number of previous states, an iterative solution is usually the best approach.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Total Characters in String After Transformations I | Medium | Solve | |
| Longest Ideal Subsequence | Medium | Solve | |
| Fraction to Recurring Decimal | Medium | Solve | |
| Integer to Roman | Medium | Solve | |
| Total Characters in String After Transformations II | Hard | Solve |