Count Number of Texts Problem
Description
LeetCode Problem 2266.
Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below.

In order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key.
- For example, to add the letter
's', Alice has to press'7'four times. Similarly, to add the letter'k', Alice has to press'5'twice. - Note that the digits
'0'and'1'do not map to any letters, so Alice does not use them.
However, due to an error in transmission, Bob did not receive Alice's text message but received a string of pressed keys instead.
- For example, when Alice sent the message
"bob", Bob received the string"2266622".
Given a string pressedKeys representing the string received by Bob, return the total number of possible text messages Alice could have sent.
Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: pressedKeys = "22233"
Output: 8
Explanation:
The possible text messages Alice could have sent are:
"aaadd", "abdd", "badd", "cdd", "aaae", "abe", "bae", and "ce".
Since there are 8 possible messages, we return 8.
Example 2:
Input: pressedKeys = "222222222222222222222222222222222222"
Output: 82876089
Explanation:
There are 2082876103 possible text messages Alice could have sent.
Since we need to return the answer modulo 10^9 + 7, we return 2082876103 % (10^9 + 7) = 82876089.
Constraints:
1 <= pressedKeys.length <= 10^5pressedKeysonly consists of digits from'2'-'9'.
Solution
Approach: Grouping + Dynamic Programming
Runs of the same key are independent, so we split pressedKeys into runs and multiply the number of ways for each run.
For a run of length i, the last 1, 2 or 3 presses (up to 4 for the keys 7 and 9) can form one letter, leaving a shorter run. With f[i] for ordinary keys and g[i] for keys 7 and 9:
f[0] = f[1] = 1,f[2] = 2,f[3] = 4, andf[i] = f[i-1] + f[i-2] + f[i-3]fori >= 4;gstarts the same way, andg[i] = g[i-1] + g[i-2] + g[i-3] + g[i-4].
All values are taken modulo 10^9 + 7.
Complexity: time O(n), space O(n), where n is the length of pressedKeys.
from itertools import groupby
mod = 10**9 + 7
f = [1, 1, 2, 4]
g = [1, 1, 2, 4]
for _ in range(100000):
f.append((f[-1] + f[-2] + f[-3]) % mod)
g.append((g[-1] + g[-2] + g[-3] + g[-4]) % mod)
class Solution:
def countTexts(self, pressedKeys: str) -> int:
ans = 1
for c, s in groupby(pressedKeys):
m = len(list(s))
ans = ans * (g[m] if c in "79" else f[m]) % mod
return ans