Count Number of Texts
Count the messages a run of phone keypad presses could spell, working back from the last letter.
On a phone keypad, each key from 2 to 9 carries letters: 2 has a, b and c, 3 has d, e and f, and so on, with four letters on 7 (p, q, r, s) and 9 (w, x, y, z). A letter is typed by pressing its key once for the first letter, twice for the second, and so on.
A message was typed this way, but only the presses arrived, as a string pressedKeys
Example 1
Output: 8
Explanation: "222" can be aaa, ab, ba or c, and "33" can be dd or e, so there are 4 × 2 = 8 messages.
Example 2
Output: 82876089
Explanation: 36 presses of the 2 key can spell 2,082,876,103 messages, and 82876089 is the remainder after dividing by 109 + 7.
The Idea
You may remember phones that had only number keys. To send a text, you pressed 2 once for a, twice for b and three times for c, and paused before the next letter. Without the pauses, a run of presses becomes ambiguous.
Look at Example 1, 2223333222
Listing the readings works for five presses. But Example 2 has 36 presses of one key and more than two billion readings. How can we count them without writing them down?
Look only at the last letter. In 222
To keep track, write ways[i]iways[0]
In the picture, each ways22222ways[2]2ways[1]ways[0]ways[3]
The 3s work the same way, except that their last letter can never reach back into the 2s, because one letter uses one key. So ways[4]ways[3]ways[5]ways[4]ways[3]
So each count is the sum of the few counts just before it, as far back as the last letter can reach.
Solution Approach
Turning that idea into code means settling three things: which counts to keep, how far back the last letter can reach, and how to keep the numbers small.
Which counts to keep
Why not just try every split? A recursive function could choose the last letter, then call itself on what is left. It would get the right answer, but the same shorter runs come up again and again, and the work grows about as fast as the number of messages, which is in the billions for Example 2.
Instead, fill an array from the front: ways[0]ways[1]ways[n]n
How far back the last letter reaches
Which earlier counts go into ways[i]kways[i - k]k
runs from 1 up to 3, or up to 4 when the key is 7 or 9.k- All
presses must be on the same key. At the first different key, stop: a longerk would mix keys too.k cannot go past the start of the string.k
Keeping the numbers small
The counts grow fast. 35 presses of the 2 key already give 1,132,436,852 messages, more than 109 + 7. The task asks for the remainder after dividing by 109 + 7, which Java computes with the remainder operator, %
Taking the remainder after every addition gives the same final remainder as taking it once at the end, and it keeps every stored value below 109 + 7. The array holds long
Java Solution
The method countTexts
- First, create the array
, whereways will be the number of messages the firstways[i] presses can spell, and seti to 1 for the empty message.ways[0] - Fill the array from the front with an outer loop over
, one press at a time. For each press, look at its key and seti , how many presses one letter can use: 4 for keys 7 and 9, and 3 for the others.maxPresses - Inside, a second loop tries each length
for the last letter, from 1 up tok . If the pressmaxPresses places back is on a different key,k stops the loop, because one letter cannot mix keys. Otherwisebreak is added toways[i - k] .ways[i] - After every addition, keep only the remainder after dividing by
, which is 109 + 7.MOD - When the outer loop is done, return
, the count for all the presses.ways[n]
The main
public class CountNumberOfTexts {
private static final int MOD = 1000000007;
public int countTexts(String pressedKeys) {
int n = pressedKeys.length();
long[] ways = new long[n + 1]; // ways[i]: messages for the first i presses
ways[0] = 1; // the empty message
for (int i = 1; i <= n; i++) {
char key = pressedKeys.charAt(i - 1);
int maxPresses = (key == '7' || key == '9') ? 4 : 3;
// the last letter used the last k presses, all on the same key
for (int k = 1; k <= maxPresses && i - k >= 0; k++) {
if (pressedKeys.charAt(i - k) != key) {
break; // one letter cannot mix keys
}
ways[i] = (ways[i] + ways[i - k]) % MOD;
}
}
return (int) ways[n];
}
public static void main(String[] args) {
CountNumberOfTexts counter = new CountNumberOfTexts();
String[] tests = {
"22233",
"222222222222222222222222222222222222",
"2",
"2222",
"7777",
"2323"
};
for (String keys : tests) {
System.out.println(keys + " -> " + counter.countTexts(keys));
}
}
}
Running it prints:
22233 -> 8
222222222222222222222222222222222222 -> 82876089
2 -> 1
2222 -> 7
7777 -> 8
2323 -> 1
The first two lines are the examples: 8 for 222332ways[0]
Now compare the next two lines. Four presses of 2 give 7, but four presses of 7 give 8. The extra message is s, the fourth letter on 7, which uses all four presses. With maxPresses7777
The last line, 2323k = 1
Complexity
Each press is visited once, and the inner loop looks back at most four presses, so the work grows in step with the length of the string.
- Time: O(n), where n is the number of presses. The outer loop runs n times, and the inner loop at most 4 times, each with one addition and one remainder.
- Space: O(n) for the
array of n + 1 values. Only the last four values are ever read, so as an optional improvement, keeping just those four would bring it down to O(1).ways
For a problem with the same shape, counting how a string of digits splits into letters, see