Decode Ways
Problem
A message made of capital letters was encoded by replacing each letter with its position in the alphabet: A became 1, B became 2, ..., Z became 26, and the digits were concatenated with no separators. You are given the resulting digit string s. Count how many different letter strings could have produced it. A group of digits is only valid if it is 1–9 or 10–26 with no leading zero; 0, 06, and 27 are not valid codes. Return 0 if no decoding exists.
sis a digit string up to about a hundred characters long, and it may start with a0.- The answer is guaranteed to fit in a normal signed integer.
Examples
s = "21"→2. Read as2,1(BA) or21(U).s = "119"→3.1,1,9(AAI),11,9(KI), and1,19(AS).s = "07"→0. A zero cannot start a code, and07is not the same code as7.
Hints
- Look at the last one or two digits of the string. Each valid decoding ends by consuming either one digit or two.
- If you knew the number of decodings of every shorter prefix, how would you combine two of them to get the count for the full string?
- This is a 1D DP over prefixes with the Fibonacci-like transition
count[i] = (count[i-1] if last digit valid) + (count[i-2] if last two digits valid).
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.