15% off all plans & roadmaps Use code

See plans

Decode Ways

Updated

TL;DR: Count the ways to split a digit string into codes 1 to 26. Each prefix count is the sum of two earlier counts, so a Fibonacci-style DP with two variables solves it in O(n) time and O(1) space.

Problem

A message is encoded as a string of digits. Each letter maps to a number: "1" is 'A', "2" is 'B', and so on up to "26", which is 'Z'.

Because some codes contain other codes ("2" and "5" versus "25"), one string can decode in several ways. For example, "11106" can become:

  • "AAJF" with the grouping (1, 1, 10, 6)
  • "KJF" with the grouping (11, 10, 6)
  • The grouping (1, 11, 06) is invalid, because "06" is not a code. Only "6" is.

Some strings cannot be decoded at all.

Given a string s made only of digits, return the number of ways to decode it. If there is no valid way, return 0. The test cases are built so the answer fits in a 32-bit integer.

Example 1

Input: s = "12"
Output: 2
Explanation: "12" decodes as "AB" (1 2) or "L" (12).

Example 2

Input: s = "226"
Output: 3
Explanation: "226" decodes as "BZ" (2 26), "VF" (22 6) or "BBF" (2 2 6).

Example 3

Input: s = "06"
Output: 0
Explanation: "06" cannot map to "F", because "06" is not the same code as "6". The string has no valid encoding, so the answer is 0.

Constraints

  • 1 <= s.length <= 100
  • s contains only digits and may contain leading zeros.

Constraints that matter

  • s.length <= 100 means a recursion that branches twice per digit can reach billions of calls in the worst case, so you need to share work between branches.
  • The recursion depth is at most 100, so recursion is safe in every language, including Python's default limit.
  • Digits may be zero, and 0 has no code alone. A zero is only usable as the second digit of 10 or 20, so every transition needs an explicit zero check.
  • The answer fits in 32 bits, but counts for long prefixes can be larger when a later zero kills the string. Intermediate sums can overflow int in some languages, so know what your language does on overflow.
  • Only the last two prefix counts are ever read, which lets you drop the full table and use O(1) extra space.

View on LeetCode

Hints

Hint 1

This is a counting problem on a string where each decision looks only at the last one or two digits.

Hint 2

Walk the string from the left.

Solution

Intuition

This is a counting problem on a string where each decision looks only at the last one or two digits. That is the signal for dynamic programming on a 1D array, the same shape as Climbing Stairs. The last code in any valid decoding is either one digit or two digits, and those two cases never overlap.

It is like a ledger that keeps only the last two monthly totals. The variable prev2 is the older total, prev1 is the newer one, and each new total cur is built from both and replaces the oldest entry.

So let dp[i] be the number of ways to decode the first i characters. If the last code is the single digit s[i-1], it must be 1 to 9, and the rest of the work is dp[i-1]. If the last code is the pair s[i-2]s[i-1], it must be 10 to 26, and the rest is dp[i-2]. Add the two cases that are allowed.

The base case is dp[0] = 1. An empty prefix has exactly one decoding: the empty one. Without that value, the first pair such as 12 would not count its L decoding.

Zeros fall out of the rules for free. A 0 adds nothing as a single digit, and it adds dp[i-2] only when the digit before it makes 10 or 20.

The recurrence reads only dp[i-1] and dp[i-2]. You can keep two variables and roll them forward, exactly as in an iterative Fibonacci. The page builds up to that: plain recursion, then memoization to remove repeated work, then the rolling-variable version.

Watch the pattern animation

Worked example

Input: s = "11106"
Output: 2
Explanation: The only valid groupings are (1, 1, 10, 6), which reads AAJF, and (11, 10, 6), which reads KJF. The zero must pair with the 1 before it as 10, and 06 is never a code. That leaves exactly two ways.

Approach 1: Brute force recursion

Walk the string from the left. At index i, try to take one digit, and try to take two digits. Count how many complete decodings each choice leads to, and add them.

A zero at the current index kills the branch, because no code starts with 0. Reaching the end of the string counts as one finished decoding. This is correct, and it is what you write first when you have not noticed the repeated work.

Steps

  1. Define count(i) as the number of ways to decode the suffix starting at index i.
  2. If i == n, return 1. The whole string has been consumed.
  3. If s[i] == '0', return 0. No code starts with zero.
  4. Start ways = count(i + 1) for taking one digit.
  5. If a second digit exists and the pair is at most 26, add count(i + 2).
  6. Return ways, and call count(0) for the answer.

Dry run

Trace "11106" by suffix index.

  • count(5) returns 1 (end of string).
  • count(4): digit 6 is fine, so it calls count(5) = 1. No second digit exists. Result 1.
  • count(3): s[3] is 0, so it returns 0.
  • count(2): take 1 gives count(3) = 0. Pair 10 is valid, so add count(4) = 1. Result 1.
  • count(1): take 1 gives count(2) = 1. Pair 11 is valid, so add count(3) = 0. Result 1.
  • count(0): take 1 gives count(1) = 1. Pair 11 is valid, so add count(2) = 1. Result 2.

Notice that count(2) and count(3) were each reached from two different parents. On longer strings that repeated work explodes.

Complexity

TimeO(2^n)
SpaceO(n)

Here n is the length of s. Each call makes at most two recursive calls and the index grows by 1 or 2, so the call tree has at most 2^n nodes. The worst case, a string such as all ones, grows like the Fibonacci numbers, which is still exponential. The recursion depth is at most n, so the stack uses O(n) space.

PythonTested in our runner

class Solution:
    def numDecodings(self, s: str) -> int:
        n = len(s)

        def count(i: int) -> int:
            if i == n:
                return 1
            if s[i] == '0':
                return 0
            ways = count(i + 1)
            if i + 1 < n and int(s[i:i + 2]) <= 26:
                ways += count(i + 2)
            return ways

        return count(0)

Approach 2: Top-down memoization

What's slow: the recursion recomputes the same suffix many times. In the trace above, count(2) and count(3) each ran twice. The number of distinct suffixes is only n + 1, yet the call tree grows exponentially.

The insight that fixes it: count(i) depends only on i, never on the path taken to reach it. Store each result the first time you compute it and return the stored value afterward. Each index is then solved once.

Steps

  1. Create a memo array of size n + 1, filled with -1 for not computed.
  2. Write count(i) as before: return 1 at the end, return 0 on a '0'.
  3. At the top of count(i), return memo[i] if it is not -1.
  4. Compute ways from count(i + 1) and, when the pair is 10 to 26, count(i + 2).
  5. Store ways in memo[i] before returning it.
  6. Return count(0).

Dry run

Same string, "11106", with a cache. Calls in order of first computation:

  • count(0) calls count(1), which calls count(2), which calls count(3).
  • count(3) sees 0 and stores memo[3] = 0.
  • count(2) then calls count(4), which calls count(5) = 1. It stores memo[4] = 1, then memo[2] = 0 + 1 = 1.
  • count(1) needs count(3) for the pair 11. This is a cache hit, 0. It stores memo[1] = 1 + 0 = 1.
  • count(0) needs count(2) for the pair 11. Another cache hit, 1. Result 1 + 1 = 2.

Two recomputations became two lookups.

Complexity

TimeO(n)
SpaceO(n)

Here n is the length of s. There are n + 1 distinct states, and each is computed once with a constant number of operations, so the time is O(n). The memo array holds n + 1 integers and the recursion depth is at most n, so the space is O(n).

PythonTested in our runner

class Solution:
    def numDecodings(self, s: str) -> int:
        n = len(s)
        memo = [-1] * (n + 1)

        def count(i: int) -> int:
            if i == n:
                return 1
            if s[i] == '0':
                return 0
            if memo[i] != -1:
                return memo[i]
            ways = count(i + 1)
            if i + 1 < n and int(s[i:i + 2]) <= 26:
                ways += count(i + 2)
            memo[i] = ways
            return ways

        return count(0)
1D Array (Fibonacci Style) pattern infographic for Decode Ways

Solution pattern

1D Array (Fibonacci Style)

Part of Dynamic Programming (DP) Patterns

Approach 3: Bottom-up DP with two variablesOptimal1D Array (Fibonacci Style)

What's slow: memoization is linear in time, but it still keeps an O(n) table and an O(n) call stack. Each state reads only the two states immediately before it, so older entries are dead weight.

The insight that fixes it: fill the prefix counts from left to right and keep only the last two. Let prev2 be dp[i-2] and prev1 be dp[i-1]. Each step computes cur from them, then slides the window forward by one. There is no recursion and no array.

Steps

  1. Set prev2 = 1 for dp[0], the empty prefix.
  2. Set prev1 = 1 if s[0] is not '0', else 0. This is dp[1].
  3. For each i from 2 to n, set cur = 0.
  4. If s[i-1] is not '0', add prev1 to cur.
  5. Compute the pair s[i-2]s[i-1] as a number. If it is 10 to 26, add prev2 to cur.
  6. Slide the window: prev2 = prev1, then prev1 = cur.
  7. After the loop, return prev1, which is dp[n].

Dry run

Trace "11106". Start with prev2 = dp[0] = 1 and prev1 = dp[1] = 1, since s[0] is 1.

isingle digit s[i-1]pairsingle addspair addscur (dp[i])prev2, prev1 after
2111prev1 = 1prev2 = 121, 2
3111prev1 = 2prev2 = 132, 3
4010none (zero)prev2 = 223, 2
5606 = 6, invalidprev1 = 2none22, 2

The loop ends with prev1 = 2, which matches the expected output. Row 4 shows the zero rule at work: dp[4] drops from 3 to 2, because the 0 can only join the 1 before it. Row 5 shows that 06 contributes nothing, so dp[5] inherits dp[4] unchanged.

Complexity

TimeO(n)
SpaceO(1)

Here n is the length of s. The loop runs n - 1 times, and each iteration does a constant number of digit comparisons and additions, so the time is O(n). Only the variables prev1, prev2 and cur are stored, regardless of n, so the extra space is O(1).

PythonTested in our runner

class Solution:
    def numDecodings(self, s: str) -> int:
        n = len(s)
        prev2 = 1  # dp[0]: empty prefix
        prev1 = 0 if s[0] == '0' else 1  # dp[1]
        for i in range(2, n + 1):
            cur = 0
            if s[i - 1] != '0':
                cur += prev1
            pair = int(s[i - 2:i])
            if 10 <= pair <= 26:
                cur += prev2
            prev2 = prev1
            prev1 = cur
        return prev1

Common mistakes

  • Adding dp[i-1] without checking s[i-1] != '0'. A lone zero has no code, so the single-digit branch must add nothing. The fix is the explicit zero test before that addition.
  • Testing the pair with int(s[i-2:i]) <= 26 alone. "06" is 6, which passes, but 06 is not a code. Require 10 <= pair <= 26, or check that the first digit is not zero.
  • Starting with dp[0] = 0. The empty prefix must count as 1 way, or every pair such as 12 loses its two-digit decoding. Set dp[0] = 1.
  • Reading s[i-2] when i = 1. Start the loop at i = 2 and set dp[1] before it, or guard the pair check with i >= 2.
  • Returning early with 0 only when the first character is zero. Zeros later in the string, as in "100" or "30", also give 0, and the recurrence handles them only if both branches reject them. Do not special-case them away.
  • Using a greedy rule such as always taking two digits when possible. For "226" that gives 22 6 and misses the other two decodings. You must count both branches at every step.
  • Updating the window in the wrong order, such as prev1 = cur before prev2 = prev1. That destroys the old prev1. Move prev2 first, then prev1.

Edge cases

  • "0": no code starts with zero, so the answer is 0.
  • "06": a leading zero makes the whole string undecodable, so the answer is 0.
  • "10": the zero is used by the pair 10, so the answer is 1, not 2.
  • "100": the final 0 has no valid partner, since 00 is not a code. The answer is 0.
  • "27": 27 is above 26, so only 2 7 works. The answer is 1.
  • "1": a single non-zero digit gives 1 and the loop never runs.
  • A hundred ones: the count is large, and tests keep the answer within 32 bits. Pay attention to overflow only if you add a custom large test.

Follow-ups interviewers ask

Can you do it in O(1) extra space?
Yes. Each dp[i] reads only dp[i-1] and dp[i-2], so keep two variables and slide them forward. That is the third approach on this page. Time stays O(n) and the table disappears.
What if the answer can be huge and you must return it modulo 10^9 + 7?
Apply the modulo after every addition, cur = (cur + prev1) % MOD. Use a 64-bit type in Java, C++ and C# so the sum of two values below MOD cannot overflow. The recurrence does not change.
What if the string can contain * as a wildcard for any digit 1 to 9?
That is Decode Ways II. Keep the same recurrence, but each transition multiplies by the number of digits the wildcard can stand for. For example * alone gives 9 single choices, and 1* gives 9 pairs. Work mod 10^9 + 7 because the counts grow quickly.

Decode Ways FAQ

What is the time complexity of Decode Ways?

The optimal DP runs in O(n) time, where n is the length of the string. It visits each position once and does constant work per position. Plain recursion without memoization is exponential, up to O(2^n).

Why use dynamic programming for Decode Ways?

The count for a prefix depends only on the counts for the prefixes one and two characters shorter. Those subproblems repeat across many branches in plain recursion. DP computes each one once, which turns an exponential search into a linear scan.

Can Decode Ways be solved in O(1) extra space?

Yes. The recurrence uses only dp[i-1] and dp[i-2], so two integer variables replace the array. The input string is read-only and is not counted as extra space.

Why does the empty prefix count as 1 way?

It acts as the identity for the sum. When the first two digits form a valid code such as 12, that code leaves an empty prefix behind, and it must contribute one decoding. Setting dp[0] = 0 would drop those counts.

How does Decode Ways handle zeros?

A zero never counts as a single digit. It only works as the second digit of 10 or 20, which the pair check allows through dp[i-2]. If the zero is preceded by anything else, both branches add nothing and the count for that prefix becomes 0.

How is Decode Ways related to Climbing Stairs?

Both use the recurrence f(i) = f(i-1) + f(i-2). In Climbing Stairs both steps are always allowed. In Decode Ways each step is allowed only when the one-digit or two-digit code is valid.

Asked at

See which companies ask this — Pro

Practise it