InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 1-D Dynamic Programming

Decode Ways

medium Original ↗ 00:00

Problem

A message of letters A–Z was encoded to digits using the mapping A → "1", B → "2", …, Z → "26". Given a string of digits s, count how many distinct original letter strings could have produced it.

To decode, s is split into groups, each group being either one digit (19) or two digits forming a value 1026. A group with a leading zero (like "06") is invalid, and a lone "0" decodes to nothing.

Return the number of valid decodings (which may be 0).

Examples

  • s = "12"2"1 2" → "AB" or "12" → "L".
  • s = "226"3"2 2 6" (BBF), "22 6" (VF), "2 26" (BZ).
  • s = "06"0 — no group can start with 0, and "06" is not a valid two-digit code.

Constraints

  • 1 <= s.length <= 100
  • s consists of digits only and may contain '0'.

The length is small, so an O(n) solution is easy to reach. The difficulty is in the zero-handling edge cases, not performance.

Think about it first

Hint 1 Scan the string and decide, at each position, whether the next code is one digit or two. The count of decodings for the rest of the string depends only on where you are — a classic 1-D DP over the index.
Hint 2 Let `ways(i)` be the number of ways to decode the suffix starting at index `i`. Take one digit (valid iff `s[i] != '0'`) and add `ways(i+1)`; take two digits (valid iff `s[i:i+2]` is between `"10"` and `"26"`) and add `ways(i+2)`. Base case `ways(n) = 1` (empty suffix, one way).
Hint 3 A `'0'` is decodable *only* as the second digit of `10` or `20`; anywhere else it forces `0` ways. Compute `ways` from the end backward, or forward with `dp[i]`; only the last two values matter, so O(1) space is possible.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug