๐Ÿ—“๏ธ Day 37: Decode Ways โ€” DP on Strings with Numbers

๐Ÿง  Concept Deep Dive

You are given a string s containing only digits. Each digit or pair of digits can represent a letter ('1' = A, ..., '26' = Z). Your task: count the number of ways to decode s.

We will use Dynamic Programming where dp[i] represents the number of ways to decode up to index i.


๐ŸŽฏ Visual Intuition

Letโ€™s say:

s = "226"
  • Can be split as "2 2 6" โ†’ B B F
  • Or "22 6" โ†’ V F
  • Or "2 26" โ†’ B Z

So 3 ways in total.

Weโ€™ll walk the string and for each position:

  • Add ways from previous if single digit is valid (1-9)
  • Add ways from previous two digits if valid (10โ€“26)

๐Ÿ› ๏ธ Code Pattern: DP with String

function numDecodings(s: string): number {
  if (!s || s[0] === '0') return 0;
  const n = s.length;
  const dp = new Array(n + 1).fill(0);
  dp[0] = 1; // empty string
  dp[1] = 1; // first char guaranteed not '0'

  for (let i = 2; i <= n; i++) {
    const one = Number(s.slice(i - 1, i));
    const two = Number(s.slice(i - 2, i));

    if (one >= 1 && one <= 9) dp[i] += dp[i - 1];
    if (two >= 10 && two <= 26) dp[i] += dp[i - 2];
  }
  return dp[n];
}

๐Ÿ“˜ Example

Input: s = "12"
Output: 2
Explanation: "AB" (1 2) or "L" (12)

Input: s = "226"
Output: 3
Explanation: "BBF", "BZ", "VF"

Input: s = "06"
Output: 0

๐Ÿงช Homework

  1. What if s contains invalid characters like letters?
  2. Modify the solution to also return one actual decoding path (any).
  3. Solve using recursion + memoization.

๐Ÿง  Big-O Cheat Sheet

  • Time: O(n)
  • Space: O(n) โ€” can be optimized to O(1) using two variables instead of an array

๐Ÿ”ฎ Up Next

โ–ถ๏ธ Day 38: Palindrome Partitioning โ€” All Ways to Split

This page was last edited on 2025-08-01 10:20

Powered by Wiki|Docs

This page was last edited on 2025-08-01 10:20

Tri Nguyen
No Copyright

Powered by Wiki|Docs