Decode Ways solution explained

Decode Ways counts how many letter strings a run of digits could stand for when A is 1, B is 2 and so on up to Z at 26. Walk the digits left to right: the count for a prefix is the count one digit back if the current digit is not 0, plus the count two digits back if the last two digits form a number from 10 to 26. Two rolling counts give an O(n) time, O(1) space solution, and zeros are where almost every bug hides.

By Published 7 min read

The task, restated

Someone wrote a word using numbers, A as 1, B as 2, and so on to Z as 26, then ran all the numbers together with no spaces. You receive only the digit string. Return how many different letter strings could have produced it. A piece may be one digit from 1 to 9 or two digits from 10 to 26. A piece can never start with 0, so 05 is not E and a lone 0 is not a letter.

Examples made up for this page
DigitsCountThe readings
261142 6 1 1, 26 1 1, 2 6 11, 26 11
1202121 20 2 1, 1 20 21 (the 0 must join the 2 before it)
1010110 10 only
2712 7; 27 is past Z
305030 is past Z and 0 cannot stand alone
1000The second 0 has nothing to pair with
Examples made up for this page. Scroll sideways on a small screen.

Ask two things before coding. Is the string guaranteed non-empty and digits only? And can the count get large? A string of n ones has a count that grows like the Fibonacci numbers, so about 92 ones in a row already overflow a signed 64-bit integer, and JavaScript numbers stop being exact at around 78 ones. Some versions ask for the count modulo a large prime for exactly this reason.

What the interviewer is checking

Decode Ways looks like string work but is a counting problem. Interviewers watch for three things: whether you see that counts for prefixes repeat, whether your recurrence adds two cases rather than picking one, and whether you treat zeros carefully. A candidate who writes the clean recurrence and then fails on 100 or 305 has missed the part that makes this problem a favorite. Testing your own code on a zero case before the interviewer does is a strong signal.

Brute force: list every reading

A recursive function can peel off one digit or two digits from the front, check the piece is legal, and recurse on the rest. Returning the actual letter strings makes the idea concrete and gives a reference to test against. The number of readings can double with each extra digit, so this is exponential in time and in output size.

def all_readings(digits):
    if digits == "":
        return [""]
    out = []
    if digits[0] != "0":
        letter = chr(ord("A") + int(digits[0]) - 1)
        out += [letter + rest for rest in all_readings(digits[1:])]
    if len(digits) >= 2 and 10 <= int(digits[:2]) <= 26:
        letter = chr(ord("A") + int(digits[:2]) - 1)
        out += [letter + rest for rest in all_readings(digits[2:])]
    return out
Exponential enumerator that returns the readings themselves.

For 2611 this returns BFAA, ZAA, BFK and ZK. Calling len on the result answers the question, slowly.

From listing to counting

Let ways(i) be the number of readings of the first i digits, with ways(0) = 1 for the empty prefix. The last piece of any reading of the first i digits is either the single digit at position i - 1 or the pair at positions i - 2 and i - 1. If that single digit is 1 to 9, every reading of the first i - 1 digits extends by one letter, which contributes ways(i - 1). If the pair reads 10 to 26, every reading of the first i - 2 digits extends, contributing ways(i - 2). The two sets of readings are different because their last pieces have different lengths, so the counts add.

Counting the prefixes of 12021
PrefixLast digit alone?Last pair 10 to 26?Count
(empty)1
1yes, adds 1no pair yet1
12yes, adds 112, adds 12
120no, 0 cannot stand alone20, adds 11
1202yes, adds 102 starts with 0, no1
12021yes, adds 121, adds 12
Counting the prefixes of 12021. Scroll sideways on a small screen.

Look at the row for 120. The count drops from 2 to 1, because the reading that ended with 12 as a single letter leaves the 0 with no partner. Zeros do not just fail to add, they force the previous digit into a pair, and that is what the table captures without any special branch.

Optimal approach: two rolling counts

def count_readings(digits):
    if not digits:
        return 0  # most statements promise a non-empty string
    before = 1                              # ways for the prefix two digits back
    latest = 0 if digits[0] == "0" else 1   # ways for the prefix one digit back
    for i in range(1, len(digits)):
        here = 0
        if digits[i] != "0":
            here += latest
        pair = int(digits[i - 1 : i + 1])
        if 10 <= pair <= 26:
            here += before
        before, latest = latest, here
    return latest
Python: O(n) time, O(1) extra space.
function countReadings(digits) {
  if (digits.length === 0) return 0;
  let before = 1;
  let latest = digits[0] === "0" ? 0 : 1;
  for (let i = 1; i < digits.length; i++) {
    let here = 0;
    if (digits[i] !== "0") here += latest;
    const pair = Number(digits.slice(i - 1, i + 1));
    if (pair >= 10 && pair <= 26) here += before;
    before = latest;
    latest = here;
  }
  return latest;
}
JavaScript: the same counting loop.

The range check 10 to 26 does double duty. It rejects pairs past Z, and it rejects pairs that start with 0, such as 05, because those read as numbers below 10. The empty string returns 0 here by choice; mathematically it has one empty reading, so say which convention you picked. Once latest and before are both 0, the count can never recover, so you may return early, though it does not change the complexity.

Time and space

Cost for a string of n digits
VersionTimeExtra space
List every readingExponential in n, plus the size of the outputExponential for the output
Recursion with a memo on the start indexO(n)O(n) memo and stack
Bottom-up array of countsO(n)O(n)
Two rolling countsO(n)O(1)
Cost for a string of n digits. Scroll sideways on a small screen.

Edge cases

  • A leading 0, as in 06: no readings at all.
  • 10 and 20: exactly one reading each, because the 0 must join the 1 or 2.
  • 30, 40 and so on inside the string: the count becomes 0 from that point on.
  • Two zeros in a row: 0 readings.
  • 27 through 29 and two-digit numbers with a nonzero second digit from 31 up: one way to split them, digit by digit. 30, 40 and so on up to 90 have none.
  • Long runs of 1s and 2s: the count grows fast, so plan for big integers or a modulus.

Mistakes to avoid

  • Checking only pair <= 26 and forgetting pair >= 10, which counts 05 as a letter.
  • Treating a 0 digit as adding latest, which makes 100 look valid.
  • Using max instead of addition, carried over from optimization problems such as House Robber.
  • Converting the whole string to an integer, which drops leading zeros and overflows on long inputs.
  • Testing only on strings without zeros, where nearly any sketch of the recurrence passes.

How to explain it out loud

Fictional example

Walking an interviewer through the count
Candidate
Every reading ends with a one-digit letter or a two-digit letter. Those are separate cases, so I add their counts instead of choosing between them.
Candidate
If the last digit is not zero, I inherit the count from one digit back. If the last two digits are between 10 and 26, I also inherit the count from two digits back.
Candidate
Let me run 100 before I call it done. Prefix 1 gives one, 10 gives one, and at 100 the last digit is zero and the pair 00 is below ten, so zero. That matches.

House Robber shares the look-back-two shape but takes a maximum where this page adds. Coin Change generalizes the look-back from 1 or 2 steps to any coin value and switches from counting to minimizing. House Robber II shows how to reuse a working linear solution when a constraint wraps around.

Where Natively fits

Zero handling is easy to miss in your own code and easy to spot in someone else's. In practice sessions on Mac or Windows, Natively can read a problem statement from your screen, suggest a counting recurrence, and point out cases like 100 to test. Its transcript of the mock lets you replay how you explained why the two cases add. See the AI interview assistant page for details.

Questions people ask

What is the recurrence for Decode Ways?

ways(i) = ways(i - 1) if the digit at i - 1 is not 0, plus ways(i - 2) if the two digits ending there read 10 to 26. Start with ways(0) = 1 for the empty prefix.

How do you handle zeros in Decode Ways?

A 0 cannot be read alone, so it adds nothing as a single digit. It only survives as the second digit of 10 or 20. Strings with 00, 30 or a leading 0 have zero readings, and the range check 10 to 26 handles all of them.

What is the time and space complexity of Decode Ways?

O(n) time for one pass over the digits. Because each step reads only the two previous counts, two variables are enough and extra space is O(1).

Why does Decode Ways add the two cases instead of taking a max?

Readings that end with a one-digit letter and readings that end with a two-digit letter are different readings, so their counts add. Taking a max would be right for an optimization problem, not a counting one.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP