Decode Ways

Count how many ways a string of digits can be read back as letters, where A is 1 and Z is 26.

Each letter is written as its place in the alphabet: 'A' becomes "1", 'B' becomes "2", and so on up to 'Z', which becomes "26". Given a string s of digits, return the number of ways to read it back as letters. A group of two digits that starts with 0, such as "06", is not a letter.

Example 1
Input: s = "12"
Output: 2
Explanation: "AB" (1 2) or "L" (12).
Example 2
Input: s = "226"
Output: 3
Explanation: "BZ" (2 26), "VF" (22 6), "BBF" (2 2 6).
Example 3
Input: s = "06"
Output: 0
Explanation: "06" is not "6", and "0" alone is no letter.
Solution

The Idea

Imagine a friend sends you a secret note where every letter was swapped for its number, and all the numbers were run together with no spaces. The note "12" could have been A then B, or the single letter L. The spaces are gone, so you have to guess where each letter ends.

Example 2 shows how the guesses multiply. The note "226" reads as 2 2 6 (BBF), as 22 6 (VF), or as 2 26 (BZ). A 0 limits the guesses instead: no letter is 0, so a 0 must be joined to the digit before it, and only "10" and "20" work. That is why "06" in Example 3 has no reading at all.

Now take a slightly longer note, "1212". Its readings are 1 2 1 2 (ABAB), 1 2 12 (ABL), 1 21 2 (AUB), 12 1 2 (LAB) and 12 12 (LL), five in all. Longer notes have far more readings, so the real question is: can we count them without writing each one out?

Look at the last letter of each reading of "1212". It is either B, from the last "2" alone, or L, from the last two digits "12". A reading that ends in B is a reading of "121" with B added, and "121" has 3 readings. A reading that ends in L is a reading of "12" with L added, and "12" has 2. So "1212" has 3 + 2 = 5 readings, without listing any of them.

A table for 1212. For the first 0, 1, 2, 3 and 4 digits the ways are 1, 1, 2, 3 and 5. A blue arrow brings the 3 ways for 121 (last letter B) and a teal arrow brings the 2 ways for 12 (last letter L) into the 5 for 1212.

In the picture above, the top row counts the digits read so far, the row labelled "beginning" shows that beginning of the note, and the row labelled "ways" shows how many readings it has. The blue arrow brings in the 3 ways for "121", the teal arrow the 2 ways for "12", and the orange box holds their sum, 5.

Every box is made the same way from the boxes to its left. The box under "121" is 2 + 1, because "121" ends either in A (after the 2 ways for "12") or in U, from "21" (after the 1 way for "1"). The box under "(nothing)" holds 1: before any digit is read there is one reading, the empty one.

Filling these boxes from left to right, so that each count is built from counts already stored for shorter beginnings of "1212", is called dynamic programming.

Solution Approach

The code rests on four decisions: whether to list the readings at all, what one table entry holds, which last letters are allowed, and, as an optional saving, how much of the table to keep.

Listing every reading

Why not try every split and count the readings found? A program that tries one digit or two at each place does find all five readings of "1212". But it reads the same endings again and again. A counted run of that program reads the ending "12" twice and the last "2" three times.

The repeats grow with the note. A note of 30 ones already has 1,346,269 readings, and a program that lists them makes at least one step per reading. The table needs one box per digit instead.

What one entry holds

What exactly goes in a box? The table is an array named dp with one entry more than the note has digits. Entry dp[i] is the number of ways to read the first i digits as letters. So for "1212", dp[3] is 3, the readings of "121", and dp[4] is 5, the answer.

Entry dp[0] stands for "(nothing)" and is set to 1. That makes the first letter work out with no special case: when the first digit is a letter, dp[1] gets the 1 from dp[0].

Which last letters are allowed

When may a reading of the first i digits end with one digit, and when with two? One digit alone is a letter unless it is 0, and then the count dp[i - 1] is added. Two digits form a letter only when they make a number from 10 to 26, and then dp[i - 2] is added.

Both checks fail for some digits, which is where the counts drop. In "2101", the box for "210" holds only 1: the 0 cannot stand alone, so the 2 ways for "21" are lost, and only 2 10 remains. A 27 is past Z, so it can only be read as 2 then 7.

Keeping only two counts

Each new box reads only the two boxes just before it. An optional improvement keeps those two counts in two variables and drops the array. The counts and the answer stay the same; only the memory shrinks.

Java Solution

The method numDecodings works in these steps:

  1. First, make the table dp, an int array of n + 1 entries, where n is the length of s. Set dp[0] to 1 for "(nothing)".
  2. A loop moves i from 1 to n, and each pass fills dp[i], the ways for the first i digits.
  3. Inside the loop, look at the i-th digit, s.charAt(i - 1). If it is not '0', it can be the last letter on its own, so add dp[i - 1].
  4. If i is at least 2, read the last two digits as a number two with Integer.parseInt(s.substring(i - 2, i)). If two is from 10 to 26, those digits can be the last letter, so add dp[i - 2].
  5. After the loop, dp[n] holds the ways for the whole string, and the method returns it.

The main method runs the three examples, "1212" from the picture, notes with zeros and a 27, and a note of 30 ones.

Java
public class DecodeWays {

    public static int numDecodings(String s) {
        int n = s.length();
        int[] dp = new int[n + 1];        // dp[i]: ways to decode the first i digits
        dp[0] = 1;                        // nothing read yet: one way, the empty one
        for (int i = 1; i <= n; i++) {
            if (s.charAt(i - 1) != '0') {
                dp[i] += dp[i - 1];       // last letter uses one digit (1-9)
            }
            if (i >= 2) {
                int two = Integer.parseInt(s.substring(i - 2, i));
                if (two >= 10 && two <= 26) {
                    dp[i] += dp[i - 2];   // last letter uses two digits (10-26)
                }
            }
        }
        return dp[n];
    }

    public static void main(String[] args) {
        String[] inputs = {"12", "226", "06", "1212", "10", "100", "2101", "27",
                "1".repeat(30)};
        for (String s : inputs) {
            System.out.println(s + " -> " + numDecodings(s));
        }
    }
}

Running it prints:

Output
12 -> 2
226 -> 3
06 -> 0
1212 -> 5
10 -> 1
100 -> 0
2101 -> 1
27 -> 1
111111111111111111111111111111 -> 1346269

The line 1212 -> 5 is the orange box in the picture. The lines 10 -> 1 and 100 -> 0 show the zero rule at work. In "10" the 0 joins the 1 to make J. In "100" the first 0 is used up the same way, and the second 0 has no partner, since "00" is not a letter either.

The line 2101 -> 1 matches the drop at "210": the one reading left is 2 10 1, or BJA. The last line, 1,346,269 readings of 30 ones, came from just 30 passes of the loop.

Why does the two-digit check need two >= 10 and not only two <= 26? Integer.parseInt("06") gives 6, which is at most 26. A run of the method without the lower bound returns 1 for "06" and 2 for "106", where the right counts are 0 and 1.

The original implementation, DecodeWays.java, is on GitHub.

Complexity

The method fills one box of the table per digit and does a fixed amount of work for each.

  • Time: O(n), because the loop fills each of the n boxes once, with one digit check, one two-digit parse and at most two additions.
  • Space: O(n), because dp keeps n + 1 counts, one for each beginning of the note; keeping only the last two counts brings it down to O(1).

Without the rules for 0 and for numbers above 26, each box is simply the sum of the two before it, as in Climbing Stairs.