PROBLEM 52 OF 75

Decode Ways

Count valid decodings of a digit string using 1→A through 26→Z.

PATTERNDynamic programmingState is the smallest information needed to finish.
SPOT THE SIGNAL

Why does this pattern fit?

FRAME · 1 OF 4

Restate the exact job

Count valid decodings of a digit string using 1→A through 26→Z.

WHY THIS FITS

A position can be reached from one valid digit or one valid two-digit number.

COMPLEXITY

O(n) time · O(1) space

COMMON FAILURE

Treating 0 as a standalone code accepts invalid strings.

THE REASONING, IN ONE PLACE

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.

Open blank recall ↗