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 with no gaps between letters. Return how many messages could have produced it. The count can be huge, so return its remainder after dividing by 109 + 7.

Example 1
Input: pressedKeys = "22233"
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
Input: pressedKeys = "222222222222222222222222222222222222"
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.
Solution

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, 22233. The 33 at the end is either dd or e. The 222 is aaa, ab, ba or c. Any reading of the 2s goes with any reading of the 3s, so there are 4 × 2 = 8 messages.

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 it is a, b or c, so it used the last one, two or three presses. What is left in front of it is a shorter run of presses, which can be counted in the same way.

To keep track, write ways[i] for the number of messages the first i presses can spell. ways[0] is 1: with no presses, the only message is the empty one.

The presses 22233 with ways[0] to ways[5] = 1, 1, 2, 4, 4, 8 below the gaps. Above the first three presses, brackets show the last letter of 222 as a, b or c, leaving ways[2], ways[1] or ways[0], so ways[3] = 2 + 1 + 1 = 4.

In the picture, each ways value sits below the gap after its presses. The three brackets above the first three presses are the choices for the last letter of 222. If it is a, the presses 22 are left, and they spell ways[2] = 2 messages. If it is b, one 2 is left, ways[1] = 1. If it is c, nothing is left, ways[0] = 1. Together that is ways[3] = 4, the four readings found by hand.

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] is just ways[3] = 4, and ways[5] = ways[4] + ways[3] = 8, the answer.

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], then ways[1], and on up to ways[n], where n is the number of presses. Each value uses only values already filled in, so every shorter run is counted once. Saving the answers to smaller versions of a problem and building on them like this is called dynamic programming.

How far back the last letter reaches

Which earlier counts go into ways[i]? Say the last letter used the last k presses. Then ways[i - k] is added, for each k that makes a real letter:

  • k runs from 1 up to 3, or up to 4 when the key is 7 or 9.
  • All k presses must be on the same key. At the first different key, stop: a longer k would mix keys too.
  • k cannot go past the start of the string.

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 values, so a sum never overflows before the remainder is taken.

Java Solution

The method countTexts works in these steps:

  1. First, create the array ways, where ways[i] will be the number of messages the first i presses can spell, and set ways[0] to 1 for the empty message.
  2. Fill the array from the front with an outer loop over i, one press at a time. For each press, look at its key and set maxPresses, how many presses one letter can use: 4 for keys 7 and 9, and 3 for the others.
  3. Inside, a second loop tries each length k for the last letter, from 1 up to maxPresses. If the press k places back is on a different key, break stops the loop, because one letter cannot mix keys. Otherwise ways[i - k] is added to ways[i].
  4. After every addition, keep only the remainder after dividing by MOD, which is 109 + 7.
  5. When the outer loop is done, return ways[n], the count for all the presses.

The main method runs both examples, a single press, four presses of the 2 key and of the 7 key, and keys that alternate.

Java
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:

Output
22233 -> 8
222222222222222222222222222222222222 -> 82876089
2 -> 1
2222 -> 7
7777 -> 8
2323 -> 1

The first two lines are the examples: 8 for 22233, and 82876089 for the 36 twos, the remainder of 2,082,876,103 after dividing by 1,000,000,007. The single 2 gives 1, which comes straight from ways[0] = 1.

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 maxPresses set to 3 for every key, 7777 would return 7 and miss it.

The last line, 2323, gives 1. No two neighbouring presses share a key, so the inner loop stops after k = 1 each time, and the only message is adad.

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 ways 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).

For a problem with the same shape, counting how a string of digits splits into letters, see Decode Ways.