#91

Decode Ways

Medium
StringDynamic ProgrammingDynamic ProgrammingRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses dynamic programming to build up the number of ways to decode the string iteratively. This avoids the overhead of recursion and reduces redundant calculations by storing intermediate results.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a DP array of size n+1, where n is the length of the string, initialized with 0.
  2. 2Step 2: Set DP[0] = 1 (an empty string has one way to be decoded).
  3. 3Step 3: Iterate through the string, updating the DP array based on valid single and double digit decodings.
  4. 4Step 4: Return DP[n] as the result.
solution.py8 lines
1def numDecodings(s):
2    if not s or s[0] == '0': return 0
3    dp = [0] * (len(s) + 1)
4    dp[0], dp[1] = 1, 1
5    for i in range(2, len(s) + 1):
6        if s[i-1] != '0': dp[i] += dp[i-1]
7        if 10 <= int(s[i-2:i]) <= 26: dp[i] += dp[i-2]
8    return dp[-1]

Complexity note: The time complexity is O(n) because we only iterate through the string once, and the space complexity is O(n) due to the DP array.

  • 1Leading zeros in the string are invalid and should be handled early.
  • 2The combinations of characters can be treated as a tree structure where each node represents a decision to take one or two characters.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.