Decode Ways
Count valid decodings of a digit string using 1→A through 26→Z.
Why does this pattern fit?
Restate the exact job
Count valid decodings of a digit string using 1→A through 26→Z.
A position can be reached from one valid digit or one valid two-digit number.
O(n) time · O(1) space
Treating 0 as a standalone code accepts invalid strings.
How to solve Decode Ways
The goal is to solve this problem from the pattern, not to memorize a finished answer. Use this as a check after your own attempt.
What the question asks
Count valid decodings of a digit string using 1→A through 26→Z.
Why Dynamic programming fits
A position can be reached from one valid digit or one valid two-digit number.
State to maintain
Ways for the previous two prefixes.
Transition
Add previous ways when current digit is nonzero and two-back ways when the pair is 10–26.
Time and space
O(n) time · O(1) space
Counterexample to the tempting mistake
Treating 0 as a standalone code accepts invalid strings.
Prove it again tomorrow
Close this page. Rebuild the state and transition from memory, write a test that exposes the mistake above, then solve a fresh input without looking back. A same-day reread is practice, not proof of retention.