MEDIUM NC#105 Blind #24 Dynamic Programming 1D
91. Decode Ways
📖 Problem
Given a string s containing only digits, return the number of ways to decode it (A=1, B=2, ..., Z=26).
🧠 Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- •Array methods (`push`, `pop`, `shift`, `slice`)
- •Object/Map/Set usage patterns
- •Function parameter and return typing
- •Array DP table updates
- •State transition thinking
- •Base case initialization
Logical Thinking Concepts
- •Define invariants before coding
- •Check edge cases first (`[]`, single element, duplicates)
- •Estimate time/space before implementation
- •Apply Dynamic Programming reasoning pattern
- •Apply Recursion reasoning pattern
💡 Approach
- → dp[i] = number of ways to decode s[0:i]
- → Single digit (1-9): add dp[i-1]
- → Two digits (10-26): add dp[i-2]
- → Handle '0' specially (can't decode '0' alone)
- → Time: O(n), Space: O(n) or O(1) optimized
🛠️ Hints & Pitfalls
Hints
- •dp[i] = number of ways to decode s[0:i]
- •Single digit (1-9): add dp[i-1]
- •Two digits (10-26): add dp[i-2]
Common Pitfalls
- •Handle '0' specially (can't decode '0' alone)
- •Time: O(n), Space: O(n) or O(1) optimized
🧪 Test Cases
Hidden tests on submit: 2
Test Case 1
Not run Input:
numDecodings('12'); Expected:
2 Test Case 2
Not run Input:
numDecodings('226'); Expected:
3 Test Case 3
Not run Input:
numDecodings('06'); Expected:
0 📝 Code Editor
📤 Output