Skip to main content
54

Decode Ways

Mediumdynamic programmingstrings

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:1-D Dynamic ProgrammingRead the beginner guide

A message of letters was encoded as digits using "A" → "1", "B" → "2", …, "Z" → "26". Given the digit string s, return the number of ways to decode it back into letters.

Understand the problem

  • Decoding means splitting the digit string into pieces, where each piece is the code of one letter (1 to 26).
  • Different splits can give different messages: "12" can be 1 | 2 ("AB") or 12 ("L"). You count the number of valid splits.
  • A piece can't start with 0: "6" is valid, but "06" isn't. And "0" alone isn't a letter.
  • If there's no valid split at all, the answer is 0.

Example 1

text
Input:  s = "12"
Output: 2

1 | 2 → "AB", or 12 → "L".

Example 2

text
Input:  s = "226"
Output: 3

2 | 26 → "BZ", 22 | 6 → "VF", 2 | 2 | 6 → "BBF".

Example 3

text
Input:  s = "06"
Output: 0

The string starts with 0, which can't be a piece on its own, and 06 isn't valid either.

Constraints

  • 1 <= s.length <= 100
  • s contains digits only. The answer fits in a 64-bit float without losing precision.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Going from the end of the string backward, the number of ways to decode from position i is the ways from i + 1 (if s[i] alone is a valid letter) plus the ways from i + 2 (if the two digits s[i]s[i+1] form a valid letter).

    The naive approach (and why it's slow)

    Try every way to split the string, recursively: take one digit or two, and recurse on the rest. The same suffixes get decoded again and again, and the number of splits grows like the Fibonacci numbers: exponential. For 100 digits, that's far too many.

    The key insight: it's Climbing Stairs with conditions

    At any position, the next piece is one digit or two digits, just like a 1-step or a 2-step in Climbing Stairs. The only difference: a step is allowed only if the piece is a valid code:

    PieceValid whenExamples
    one digit s[i]it isn't '0'"6" ✓, "0" ✗
    two digits s[i..i+1]it's between 10 and 26"12" ✓, "26" ✓, "27" ✗, "06" ✗

    Define ways(i) = the number of ways to decode the suffix starting at position i:

    text
    ways(n) = 1      (nothing left to decode: exactly one way, "do nothing")
    ways(i) = (one digit valid  ? ways(i + 1) : 0)
            + (two digits valid ? ways(i + 2) : 0)

    The answer is ways(0). Fill it from the end backward, so ways(i + 1) and ways(i + 2) are ready when you need them. As in Climbing Stairs, only the next two values matter, so two variables (next, nextNext) are enough.

    A small simplification in the code: if s[i] is '0', neither piece is valid (both would start with 0), so ways(i) = 0. Otherwise the two-digit piece is automatically at least 10, so only <= 26 needs checking.

    Step by step

    s = "226" (length 3). Start with next = ways(3) = 1 and nextNext = 0 (there's no ways(4)):

    iDigitOne digit valid?Two digitsways(i)After: next, nextNext
    26✓ → ways(3) = 1(none: last digit)11, 1
    12✓ → ways(2) = 126 ✓ → ways(3) = 11 + 1 = 22, 1
    02✓ → ways(1) = 222 ✓ → ways(2) = 12 + 1 = 33, 2

    Answer: ways(0) = 3.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n). One pass from the end.
    • Memory: O(1). Two variables.

    Common mistakes

    • Treating "0" as a letter. It isn't, so a lone 0 contributes nothing.
    • Accepting "06"-style pieces (a leading zero). Valid two-digit codes are only 10 to 26.
    • Forgetting that "10" and "20" are fine as two-digit pieces, even though their 0 can't stand alone.
    • Getting the base case wrong. ways(n) must be 1, not 0, or every count collapses to zero.

    Going deeper

    The tricky cases are all about zeros: "100" → 0 (the last 0 can't be alone, and "00" isn't a code), "2101" → 1 (2 | 10 | 1). Check your solution against these by hand. The same "count the ways to split a string into valid pieces" idea is the core of Word Break, where the pieces are dictionary words.

    Reference solution

    js
    /**
     * @param {string} s
     * @return {number}
     */
    export default function numDecodings(s) {
      // ways(i) = ways to decode s[i..]. We fill it from the end, keeping only the next two values.
      let next = 1 // ways(i + 1). Starts as ways(n) = 1: one way to decode nothing.
      let nextNext = 0 // ways(i + 2)
      for (let i = s.length - 1; i >= 0; i--) {
        let current = 0
        // A piece can't start with '0', so if s[i] is '0', ways(i) stays 0.
        if (s[i] !== '0') {
          current = next // one-digit piece s[i] (1-9): then decode the rest from i + 1
          // Two-digit piece s[i..i+1]: valid when it's <= 26 (it's >= 10, since s[i] isn't '0').
          const pair = Number(s.slice(i, i + 2))
          if (i + 1 < s.length && pair <= 26) current += nextNext
        }
        // Slide back one position (both at once).
        ;[nextNext, next] = [next, current]
      }
      return next // ways(0)
    }
    ts
    export default function numDecodings(s: string): number {
      // ways(i) = ways to decode s[i..]. We fill it from the end, keeping only the next two values.
      let next = 1 // ways(i + 1). Starts as ways(n) = 1: one way to decode nothing.
      let nextNext = 0 // ways(i + 2)
      for (let i = s.length - 1; i >= 0; i--) {
        let current = 0
        // A piece can't start with '0', so if s[i] is '0', ways(i) stays 0.
        if (s[i] !== '0') {
          current = next // one-digit piece s[i] (1-9): then decode the rest from i + 1
          // Two-digit piece s[i..i+1]: valid when it's <= 26 (it's >= 10, since s[i] isn't '0').
          const pair = Number(s.slice(i, i + 2))
          if (i + 1 < s.length && pair <= 26) current += nextNext
        }
        // Slide back one position (both at once).
        ;[nextNext, next] = [next, current]
      }
      return next // ways(0)
    }
    python
    def num_decodings(s: str) -> int:
        # ways(i) = ways to decode s[i:]. We fill it from the end, keeping only the next two values.
        # nxt starts as ways(n) = 1 (one way to decode nothing); nxt_nxt is ways(i + 2).
        nxt, nxt_nxt = 1, 0
        for i in range(len(s) - 1, -1, -1):
            current = 0
            # A piece can't start with "0", so if s[i] is "0", ways(i) stays 0.
            if s[i] != "0":
                current = nxt  # one-digit piece s[i] (1-9): then decode the rest from i + 1
                # Two-digit piece: valid when it's <= 26 (it's >= 10, since s[i] isn't "0").
                if i + 1 < len(s) and int(s[i : i + 2]) <= 26:
                    current += nxt_nxt
            # Slide back one position (both at once).
            nxt, nxt_nxt = current, nxt
        return nxt  # ways(0)