SDE & MLE Prep

91. Decode Ways

Problem

A message of letters was encoded as numbers with A → 1, B → 2, …, Z → 26 and concatenated. Given the digit string s, count the ways to decode it. Pieces like "06" are invalid (no leading zeros).

Example: "226" → 3 (2 2 6, 22 6, 2 26); "06" → 0

Constraints: length ≤ 100; the answer fits in 32 bits.

dp[i] = ways to decode s[:i]. Add dp[i−1] if s[i−1] ≠ '0'; add dp[i−2] if s[i−2:i] is in 10..26.

s = "226"
dp[0]=1  "2"->1  "22"->2 (2,2 | 22)  "226"->3 (2,2,6 | 22,6 | 2,26)

Complexity: O(n) time, O(1) space.

class Solution:
    def numDecodings(self, s: str) -> int:
        a, b = 1, 1 if s[0] != "0" else 0      # dp[i-2], dp[i-1]
        for i in range(2, len(s) + 1):
            cur = b if s[i - 1] != "0" else 0
            if 10 <= int(s[i - 2:i]) <= 26:
                cur += a
            a, b = b, cur
        return b