InterviewPrepKit

Home / Coding / 1-D Dynamic Programming

Decode Ways

medium Original β†—
Solving tips
  • This is Climbing Stairs with validity gates: ways(i) = ways(i+1) [if s[i]!='0'] + ways(i+2) [if s[i:i+2] in 10..26].
  • The whole difficulty is zeros: a '0' is only valid as the second digit of 10 or 20, otherwise that suffix contributes 0 ways.
  • Guard i+1 < n before reading a two-digit pair, and enforce both bounds 10 and 26 (so '01' and '27' are rejected).
  • Seed the base case ways(n)=1 (empty suffix) and collapse to two rolling scalars for O(n) time, O(1) space.

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 (1–9) or two digits forming a value 10–26. 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'.

Small length, so O(n) is trivial to hit; the difficulty is entirely 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.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.