Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 91 Decode Ways - Implementation

The code

Here is the implementation for Decode Ways (LeetCode 9191):

function numDecodings(s)
    n := length of s
    dp := array of size n + 1, all set to 0
    dp[n] := 1
    for i from n - 1 down to 0
        if s[i] = '0' then
            dp[i] := 0
        else
            dp[i] := dp[i + 1]
            if i + 1 < n then
                twoDigit := integer value of s[i..i+1]
                if twoDigit >= 10 and twoDigit <= 26 then
                    dp[i] := dp[i] + dp[i + 2]
    return dp[0]

The tricky part is handling '00' correctly. A '00' can never be decoded alone, so dp[i] stays 00 when s[i] is '00'. For all other digits, you take dp[i+1] (one digit) and optionally add dp[i+2] if the two-digit number falls in 1010-2626. Trace through "226226" to verify: dp[3]=1, dp[2]=1, dp[1]=2, dp[0]=3.

Time complexity: O(n)O(n).

Space complexity: O(n)O(n), reducible to O(1)O(1) by tracking only the last two values.