sagelearnai

Decode Ways

Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #91

Letters are encoded as numbers: A → 1, B → 2, …, Z → 26. Given a string of digits s, count the ways to decode it back into letters. A group can't have a leading zero ("06" is invalid), and "0" alone maps to nothing.

Examples

text
s = "12"    →  2    ("AB" from 1,2 or "L" from 12)
s = "226"   →  3    (2,2,6 · 22,6 · 2,26)
s = "06"    →  0
s = "2101"  →  1    (2,10,1)

Hints

  1. Like Climbing Stairs: the last group is either one digit or two digits.
  2. A single digit is valid if it's not '0'. Two digits are valid if they form 10–26.

Approach

State: dp[i] = ways to decode s[:i]. Base: dp[0] = 1. Then:

  • if s[i−1] != '0': dp[i] += dp[i−1] (a one-digit group),
  • if 10 ≤ int(s[i−2:i]) ≤ 26: dp[i] += dp[i−2] (a two-digit group).

Roll two variables for O(1) space.

Complexity

Time: O(n). Space: O(1).

Python solution
def numDecodings(s):
    prev2, prev1 = 0, 1          # dp[i-2], dp[i-1] with dp[0] = 1
    for i in range(1, len(s) + 1):
        cur = 0
        if s[i - 1] != "0":
            cur += prev1
        if i >= 2 and 10 <= int(s[i - 2:i]) <= 26:
            cur += prev2
        prev2, prev1 = prev1, cur
    return prev1
JavaScript solution
function numDecodings(s) {
  let prev2 = 0, prev1 = 1;
  for (let i = 1; i <= s.length; i++) {
    let cur = 0;
    if (s[i - 1] !== '0') cur += prev1;
    if (i >= 2) { const two = Number(s.slice(i - 2, i)); if (two >= 10 && two <= 26) cur += prev2; }
    [prev2, prev1] = [prev1, cur];
  }
  return prev1;
}