</>

91. Decode Ways

Medium NeetCode 150
1-D Dynamic Programming Time O(N) Space O(1)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
1-D Dynamic Programming
Time
O(N)
Space
O(1)

Standard Solution (C++)

SummaryGiven a string of digits, count the number of distinct ways it can be decoded where '1'-'26' each map to a letter ('A'-'Z'), treating leading zeros as invalid.

Approach
  • Use space-optimized DP: dp[i] = number of ways to decode the first i characters.
  • A single digit at position i contributes dp[i-1] ways if it is non-zero (not '0').
  • A two-digit number formed by positions i-1 and i contributes dp[i-2] ways if it falls in [10, 26].
  • Rolling two variables (prev2, prev1) replaces the full array, giving O(1) space.
#include <string>
using namespace std;

class Solution {
public:
    int numDecodings(const string& s) {
        if (s.empty() || s[0] == '0') return 0;

        // prev2 = dp[i-2], prev1 = dp[i-1]
        // Base: dp[0] = 1 (empty prefix), dp[1] = 1 (first char already validated)
        int prev2 = 1, prev1 = 1;

        for (int i = 1; i < (int)s.size(); ++i) {
            int cur = 0;

            // Single-digit decode: valid if current char is not '0'
            if (s[i] != '0')
                cur += prev1;

            // Two-digit decode: valid if the pair is in [10, 26]
            int twoDigit = (s[i - 1] - '0') * 10 + (s[i] - '0');
            if (twoDigit >= 10 && twoDigit <= 26)
                cur += prev2;

            prev2 = prev1;
            prev1 = cur;
        }

        return prev1;
    }
};
Time O(n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    int numDecodings(string s) {

        int len=s.length();
        if(len==0 || s[0]=='0'){
            return 0;
        }

        int prev2=1;
        int prev1=1;

        for(int i=1; i<len; ++i){
            int cur=0;
            if(s[i]!='0'){
                cur+=prev1;
            }
            int twoDigits=stoi(s.substr(i-1, 2));
            if(twoDigits>=10 && twoDigits<=26){
                cur+=prev2;
            }
            prev2=prev1;
            prev1=cur;
            if(prev1==0){
                return 0;
            }
        }
        return prev1;
    }
};

// Time Complexity: O(N)
// Space Complexity: O(1)
Time O(N) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern