Scrivio Interview library
Dynamic programmingDynamic programmingReported 15 times · 16 min read · updated 15 November 2026

With A = 1, B = 2 and so on, count the ways a string of digits can be decoded into letters.

1What the question asks, told as a secret note with no spaces

Imagine a friend who sends you a secret note in a simple code. Every letter is written as its place in the alphabet, so A is 1, B is 2, and so on up to Z, which is 26. But your friend forgot the spaces, and the note arrives as one long row of digits. Reading it, you keep hitting the same doubt. Is this 1 an A on its own, or the start of 12, which is L? The question asks how many different messages the note could stand for.

Said more exactly, we are given a string of digits and must count the ways to cut it into pieces where every piece is a number from 1 to 26. Each such cutting is called a decoding. One rule makes the problem interesting. No letter is written as 0, and no letter's number starts with 0, so a 0 can only appear as the second digit of 10 or 20. A piece such as 06 is not allowed, even though 6 is F.

Let us keep one example for the whole article, the note 1210, and decode it by hand, reading from the left as you would read the note. The first letter is either 1 (A) or 12 (L). Suppose it is A; the rest is 210. Its first letter is 2 (B) or 21 (U). After A and B we are left with 10, which must be J, because the 0 cannot stand alone; that gives ABJ. After A and U we are left with a lone 0, a dead end. Now suppose the first letter is L; the rest is 10, which again must be J, giving LJ. So the answer is 2.

That small search shows the whole problem. At every step there is a choice of one digit or two, and some choices die at a 0. Longer notes seem to need a huge search, but the problem is smaller than it looks, and one walk from left to right with two numbers will be enough.

PictureThe example digits and their two readings

Four digits, two ways to read them. The marked digits 1 and 0 must always be read together as 10.

  1. 10211203
    reading 1
    1 2 10 = ABJ
    reading 2
    12 10 = LJ
    answer
    2

    1The digits 1, 2, 1, 0 can be read as 1 2 10 (ABJ) or as 12 10 (LJ), so the answer is 2. The final 0 is no letter alone, so it must join the 1 before it.

What to assume

Is the string made only of digits, and never empty?
We assume so.
What if it cannot be decoded at all, as with 06?
Then the answer is 0.
How long can it be?
Perhaps a hundred digits, and we assume the count fits in an int, as the usual version of the question promises. The code does not check this: the count passes the int limit at 46 digits of 1s.

A careful candidate asks a few questions first. Is the string made only of digits, and never empty? We assume so. What if it cannot be decoded at all, as with 06? Then the answer is 0. How long can it be? Perhaps a hundred digits, and we assume the count fits in an int, as the usual version of the question promises. The code does not check this, and we come back to the limit at the end.

2How to recognise that this is dynamic programming

A beginner reading this question often tries to write out every decoding, perhaps with loops that try each place to cut. That is natural, because we just did it by hand. But notice that the question never asks for the messages themselves, only how many there are. Counting can be far cheaper than listing, and that is the first clue.

The second clue is the choice. At each position we either read one digit or read two, and each choice leaves a shorter row of digits to decode. When a problem keeps making the same kind of choice and leaves a smaller problem of the same kind behind, its answer can be built from the answers of smaller problems.

The third clue is the one that settles it. Different choices lead to the same leftover digits. In our search, reading 1 and then 2 left us with 10, and reading 12 at once also left us with 10. The two paths arrived at the same question, how many ways can 10 be decoded, and a plain search would answer it twice.

Those clues point to the dynamic programming pattern, a grand name for a modest idea. We break the problem into smaller questions of the same kind, called subproblems, answer each one only once, write the answer down, and build bigger answers from smaller ones. The rule to carry to new problems is this pairing: a question that counts ways or asks for a best value, with a choice at every step, where different choices reach the same smaller question.

Two neighbours look similar. Backtracking, which tries every choice and undoes it, is the right tool for listing every decoding, but listing can cost far more than counting. A greedy rule, such as always reading two digits when they make a letter, finds only LJ on 1210 and misses ABJ. And the stairs puzzle, climbing one or two steps at a time, is a close cousin with extra rules about which steps are allowed.

3The honest first attempt, a brute force that tries both choices

The honest first attempt, the brute force, simply follows the hand search we did on the note. To count the decodings from position i onward, we try reading one digit and count what remains, and if the next two digits make a number up to 26, we also try reading two and count what remains. Two stopping rules finish the search. If i has reached the end of the string, we have read the whole note, and that is one complete decoding. If the digit at i is 0, no letter can start here, so there are none.

The picture draws every call this makes on 1210. Each box is labelled with the digits it still has to decode, and the boxes marked done are the complete decodings.

Step throughEvery call the brute force makes on 1210

Each box is one call, labelled with the digits it still has to decode. A left child takes one digit, a right child takes two.

  1. 1210210101000done0done
    calls
    9

    1The first call must decode 1210. It tries reading 1 alone, leaving 210, and reading 12, leaving 10. Each of those calls splits again in the same way.

  2. 1210210101000done0done
    calls
    9
    ways found
    2

    2Two calls reach the end of the digits, marked done, and each one counts as a decoding. Three calls start at a lone 0 and return 0 at once.

  3. 1210210101000done0done
    calls
    9
    different
    5

    3The call for 10 is made twice and the call for 0 three times. Nine calls, yet only five different questions were ever asked.

Java
// Brute force: from position i, try one digit and, if it makes a letter, two digits.
static int count(String s, int i) {
if (i == s.length()) return 1; // decoded everything: one way
if (s.charAt(i) == '0') return 0; // no letter starts with 0
int ways = count(s, i + 1); // take one digit
if (i + 1 < s.length() && Integer.parseInt(s.substring(i, i + 2)) <= 26) {
ways += count(s, i + 2); // take two digits
}
return ways;
}

Let us read it in the order it runs. The two if lines at the top are the stopping rules, end reached and lone 0. Then ways = count(s, i + 1) reads one digit, and the second if reads two digits when they form a number up to 26. Because the 0 check came first, the two digits never start with 0, so 06 is never accepted.

Now let us count. On 1210 the method makes nine calls, as the picture shows, to find two decodings. That does not sound like much, but each call can make two more, so the calls multiply as the note grows. On a note of thirty 1s, where every pair is a letter, it makes 3,524,577 calls. The number of calls grows like the Fibonacci numbers, about 1.6 times more for every extra digit, which we call exponential growth. Its space is the depth of the calls, O(n), read as order n.

So where is the waste? Look again at the last frame. The question how many ways can 10 be decoded was asked twice, and the question about a lone 0 three times. Yet there are only five different questions in total, one for each place the leftover digits can start. So the question to ask is whether we could answer each of those five questions once, and simply look the answer up the next time.

4From repeated questions to a table of counts

We could keep the recursion and store each answer the first time we compute it, which is called memoization. But a plainer way needs no recursion at all and reads the note as a person does, from left to right, asking about the digits before position i instead of after it.

So let us name the smaller question. dp[i] is the number of ways to decode the first i digits, a piece at the front of the string called a prefix. For 1210, dp[2] counts the readings of 12, and dp[4], the whole note, is our answer. The name dp is simply the usual name for a table of subproblem answers.

Now comes the step where beginners get stuck, so let us take it slowly. Think about the last letter of any reading of the first i digits. It was made either from the last digit alone or from the last two digits together; there is no third way. If the last digit alone is a letter, 1 to 9, then the digits before it can be read in dp[i - 1] ways, and each of those ways ends with this letter. If the last two digits together make a letter, 10 to 26, the digits before them can be read in dp[i - 2] ways. The two groups never overlap, so dp[i] is the sum of whichever groups are allowed.

Why 10 to 26 and not 1 to 26 for the pair? Because a pair whose first digit is 0, such as 06, would be a number below 10, and no letter is written with a leading 0. The test two >= 10 is what turns 06 away.

A beginner then asks what dp[0] should be. It counts the readings of the empty prefix, no digits at all, and it is tempting to say 0. But think of 12 read as L. Its last letter used both digits, so it adds dp[0], the readings of nothing before L. There is exactly one way to read nothing, the empty message, so dp[0] = 1; with 0 we would lose every reading that starts with a two-digit letter.

Written as code, this middle step is a short loop over an array, and the table after it fills our example in by hand.

Java
// The middle step: one count per prefix, kept in an array.
static int numDecodings(String s) {
int n = s.length();
int[] dp = new int[n + 1];
dp[0] = 1; // the empty prefix
dp[1] = s.charAt(0) == '0' ? 0 : 1;
for (int i = 2; i <= n; i++) {
int one = s.charAt(i - 1) - '0';
int two = (s.charAt(i - 2) - '0') * 10 + one;
if (one >= 1) dp[i] += dp[i - 1];
if (two >= 10 && two <= 26) dp[i] += dp[i - 2];
}
return dp[n];
}
Filling dp for 1210 by hand
iPrefixLast digit aloneLast two togetherdp[i]
0(empty)--1
111 is a letter-1
2122: add dp[1] = 112: add dp[0] = 12
31211: add dp[2] = 221: add dp[1] = 13
412100: not a letter10: add dp[2] = 22

In the table the count falls at i = 4, which is the 0 at work. The 0 alone is no letter, so dp[3] adds nothing, and only the pair 10 helps, bringing dp[2] = 2.

Look closely at the loop. To fill dp[i] it reads only dp[i - 1] and dp[i - 2]; every older entry is written once and never read again. So two variables are enough. We call them oneBack, for dp[i - 1], and twoBack, for dp[i - 2], and after each step we move them along by one place. That brings the extra memory down from O(n) to O(1), which means a fixed amount whatever the length of the note.

5Watching the two counts walk along 1210

The picture runs the final program on 1210. Its i is the length of the prefix being counted, so the digit marked as now is the last digit of that prefix, at index i - 1, and the one marked as compared is the digit before it, which pairs with it. The panel shows the two numbers the loop looks at, current, and the two counts we carry along.

Watch the frames in pairs. In the first frame of each pair, current is built from the two checks; in the second, twoBack and oneBack move along by one place.

Step throughCounting the readings of 1210 with two variables

i is the length of the prefix being counted. The marked digit is the last one of that prefix; the compared one pairs with it.

  1. 10211203
    i
    -
    one, two
    -
    current
    -
    twoBack
    1
    oneBack
    1

    1Before the loop, twoBack = 1 counts the empty prefix, and oneBack = 1 counts the prefix 1, because 1 is a letter.

  2. 10211203
    i
    2
    one, two
    2, 12
    current
    2
    twoBack
    1
    oneBack
    1

    2For i = 2 the last digit is 2, a letter, so we add oneBack, 1. The pair 12 is a letter too, so we add twoBack, 1. current is 2.

  3. 10211203
    i
    2
    one, two
    2, 12
    current
    2
    twoBack
    1
    oneBack
    2

    3The two counts move along: twoBack takes the old oneBack, 1, and oneBack takes current, 2. The prefix 12 has two readings.

  4. 10211203
    i
    3
    one, two
    1, 21
    current
    3
    twoBack
    1
    oneBack
    2

    4For i = 3 the last digit 1 is a letter, so we add oneBack, 2. The pair 21 is a letter, so we add twoBack, 1. current is 3.

  5. 10211203
    i
    3
    one, two
    1, 21
    current
    3
    twoBack
    2
    oneBack
    3

    5The counts move along again: twoBack becomes 2 and oneBack becomes 3. The prefix 121 has three readings.

  6. 10211203
    i
    4
    one, two
    0, 10
    current
    2
    twoBack
    2
    oneBack
    3

    6For i = 4 the last digit is 0, which is no letter, so oneBack adds nothing. The pair 10 is a letter, so we add twoBack, 2. current is 2.

  7. 10211203
    i
    4
    one, two
    0, 10
    current
    2
    twoBack
    3
    oneBack
    2

    7The counts move along a last time: twoBack becomes 3 and oneBack becomes 2. The count fell from 3 to 2 because of the 0.

  8. 10211203
    i
    -
    one, two
    -
    current
    -
    twoBack
    3
    oneBack
    2

    8i would be 5, past the end, so the loop stops. oneBack holds the count for all four digits, and numDecodings returns 2.

Let us read the important frames back. At i = 2 both checks pass, 2 alone and 12 together, so current = 1 + 1 = 2, the two readings AB and L of the prefix 12. At i = 3 both pass again, 1 alone and 21 together, so current = 2 + 1 = 3, the readings ABA, AU and LA of 121.

At i = 4 the 0 shows its effect. The last digit alone fails, so oneBack, 3, is not added; the three readings of 121 cannot simply have a letter tacked on. Only the pair 10 passes, adding twoBack, the 2 readings of 12. These are the readings ABJ and LJ we found by hand, and the program returns 2.

6The complete Java program

Here is the full program, the two-variable version. main counts our example and four edge cases, and each comment shows what that line prints.

Java
public class DecodeWays {
// Number of ways to decode a digit string with 1 = A, 2 = B, ..., 26 = Z.
static int numDecodings(String s) {
if (s.isEmpty()) return 0;
int twoBack = 1; // ways to decode the empty prefix
int oneBack = s.charAt(0) == '0' ? 0 : 1; // ways to decode the first digit
for (int i = 2; i <= s.length(); i++) {
int current = 0;
int one = s.charAt(i - 1) - '0'; // last digit alone
int two = (s.charAt(i - 2) - '0') * 10 + one; // last two digits together
if (one >= 1) current += oneBack; // 1..9 is a letter
if (two >= 10 && two <= 26) current += twoBack; // 10..26 is a letter
twoBack = oneBack;
oneBack = current;
}
return oneBack;
}
public static void main(String[] args) {
System.out.println(numDecodings("1210")); // 2
System.out.println(numDecodings("226")); // 3
System.out.println(numDecodings("06")); // 0
System.out.println(numDecodings("100")); // 0
System.out.println(numDecodings("27")); // 1
}
}

Let us read numDecodings in the order it runs. An empty string returns 0 at once. Then twoBack = 1 is dp[0], the one way to read nothing, and oneBack is dp[1], which is 1 unless the first digit is 0. A note that starts with 0 therefore begins with a count of 0.

The loop runs i from 2 up to the length of the string. Inside, current starts at 0. one is the last digit of the prefix, found with charAt(i - 1) - '0', which turns the character '7' into the number 7. two is the last two digits as a number, the tens digit times 10 plus one.

Then come the two checks from our rule. If one >= 1, the last digit is a letter, so we add oneBack. If two is between 10 and 26, the pair is a letter, so we add twoBack. The last two lines move the counts along, and their order matters. twoBack = oneBack must come first, because if we wrote oneBack = current first, the old oneBack would be lost before twoBack could take it. This swap in the wrong order is the most common bug in this program.

When the loop ends, oneBack holds the count for the whole string, and we return it. For a single digit the loop never runs, and oneBack is already the answer. So main prints 2, 3, 0, 0 and 1.

7How much it costs, and the zeros at the edges

Let us count on the example first. The loop ran three times for four digits, with a few additions and comparisons each time, against nine calls for the brute force. For n digits it runs n - 1 times, so the time is O(n). Whatever the length, we keep the same few int variables, so the extra space is O(1).

Comparing the ways to count decodings
ApproachTimeExtra space
Plain recursion over choicesabout 1.6^n callsO(n) call stack
Recursion that remembers answersO(n)O(n)
dp array, left to rightO(n)O(n)
Two variables, left to rightO(n)O(1)

The zeros deserve one more look, because they cause most of the wrong answers. A note starting with 0, such as 06, makes oneBack 0 from the start, and nothing later rescues it. A 0 after a digit other than 1 or 2, as in 30, gives a step where neither check passes, so current is 0, and since every later count is built from that 0, the answer is 0. In 100 the first 0 pairs with the 1 as 10, but the second 0 has no partner, so again the answer is 0. And 27 has a single reading, BG, because 27 is not a letter.

One more edge is size. For very long notes the count grows like the Fibonacci numbers and passes the int limit at 46 digits of 1s. If that can happen, we use a long, or the question asks for the count modulo a large prime, and we take that remainder at every step.

8Follow-up questions

How would you write the top-down version with memoization?

We keep the brute force and add an Integer array, memo, with one place per position. After the two stopping rules, count(s, i) returns memo[i] if it is filled; otherwise it computes ways as before, stores it in memo[i], and returns it. Each of the n + 1 positions is now computed once, so the time is O(n), with O(n) space for the array and the waiting calls. It is a fine answer, but the loop needs no recursion and only O(1) space.

How would you list every decoding instead of counting them?

That calls for backtracking with a StringBuilder. At each position we try one digit, if it is not 0, append its letter, call ourselves on the rest, and delete the letter again; then we do the same for two digits if they make 10 to 26. Each time we reach the end, we save the message. The time grows with the number of messages times n, which can be exponential, and that cannot be avoided, because the output itself can be that large.

What changes if the note may contain *, meaning any digit from 1 to 9?

The rule keeps its shape, but each check now counts how many letters a piece can stand for. A lone * can be any of 9 letters, so it adds 9 times oneBack. A pair 1* can be 11 to 19, nine letters; 2* can be 21 to 26, six; *d can be 1d or 2d, so two letters if d is at most 6 and one otherwise; and ** gives 15. The counts become huge, so the question asks for them modulo 1,000,000,007. It is still one pass, O(n) time and O(1) space.

9Conclusion

We counted the decodings of a digit string by asking, for each prefix, how its last letter was made. dp[i] adds dp[i - 1] when the last digit is 1 to 9 and dp[i - 2] when the last two digits are 10 to 26, starting from dp[0] = 1, and two variables carry everything each step needs, for O(n) time and O(1) space. The clue to remember is counting the ways, with a choice at every step, where different choices reach the same smaller question: that is dynamic programming.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me clarify the zero rules first. No letter is 0, so a 0 must be the second digit of 10 or 20, and a piece like 06 is not a letter.

Then, if they want more

I will return 0 when the string cannot be decoded. The brute force is a recursion that, at each position, reads one digit if it is not 0, or two digits if they make 10 to 26, and counts the complete readings. It grows exponentially and solves the same leftover digits many times.

Counting ways with a choice at each step and repeated subproblems means dynamic programming. Let dp of i be the number of ways to decode the first i digits, with dp of 0 equal to 1 for the empty prefix.

Then dp of i gets dp of i minus 1 if the last digit is 1 to 9, plus dp of i minus 2 if the last two digits are 10 to 26. Each step only needs the previous two values, so I keep two variables instead of an array, which gives O(n) time and O(1) space.

I would test a leading zero, a zero after a digit other than 1 or 2, such as 30, and a single digit.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 15 times in that collection. How it is counted
Official documentation
java.util, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "With A = 1, B = 2 and so on, count the ways a string of digits can be decoded into...": https://scrivio-interview-library.netlify.app/data-structures/solutions/with-a-1-b-2-and-so-on-count-the-ways-a-string-of-digits-can-be-1cbe22/