Data Structures & Algorithms Dynamic Programming — 1D
💡
Exercise 129

Decode Ways 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

A message of digits can be decoded where '1'→A, '2'→B, ..., '26'→Z. Given a digit string, count the number of ways to decode it.

s = "226" # 2|2|6 → BBF # 22|6 → VF # 2|26 → BZ # Answer: 3 ways

dp[i] = ways to decode s[:i]. If s[i-1] != '0', dp[i] += dp[i-1]. If s[i-2:i] is 10-26, dp[i] += dp[i-2].

💡 Pro tip: Understand this problem deeply — don't just memorize the code. Try explaining the approach out loud as if teaching a friend. If you can explain it simply, you truly understand it!

📋 Instructions
Count decoding ways for 's = "226"'.
dp[0]=1 (empty), dp[1]=1 if s[0]!='0'. For each i, check 1-digit and 2-digit options.
🧪 Test Cases
Input
numDecodings('226')
Expected
3
Test case 1
Input
numDecodings('12')
Expected
2
Test case 2
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.