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
Example 1
Output: 2
Explanation: "AB" (1 2) or "L" (12).
Example 2
Output: 3
Explanation: "BZ" (2 26), "VF" (22 6), "BBF" (2 2 6).
Example 3
Output: 0
Explanation: "06" is not "6", and "0" alone is no letter.
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.
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 dpdp[i]dp[3]dp[4]
Entry dp[0]dp[1]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]dp[i - 2]
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
- First, make the table
, andp array of n + 1 entries, where n is the length ofint . Sets to 1 for "(nothing)".dp[0] - A loop moves
from 1 to n, and each pass fillsi , the ways for the first i digits.dp[i] - Inside the loop, look at the i-th digit,
. If it is nots.charAt(i - 1) , it can be the last letter on its own, so add'0' .dp[i - 1] - If
is at least 2, read the last two digits as a numberi withtwo . IfInteger.parseInt(s.substring(i - 2, i)) is from 10 to 26, those digits can be the last letter, so addtwo .dp[i - 2] - After the loop,
holds the ways for the whole string, and the method returns it.dp[n]
The main
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:
12 -> 2
226 -> 3
06 -> 0
1212 -> 5
10 -> 1
100 -> 0
2101 -> 1
27 -> 1
111111111111111111111111111111 -> 1346269
The line 1212 -> 510 -> 1100 -> 0
The line 2101 -> 1
Why does the two-digit check need two >= 10two <= 26Integer.parseInt("06")
The original implementation,
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
keeps n + 1 counts, one for each beginning of the note; keeping only the last two counts brings it down to O(1).dp
Without the rules for 0 and for numbers above 26, each box is simply the sum of the two before it, as in