KatInterview

Ways to Decode a Numeric String into Letters

Dynamic ProgrammingAuto-graded · 24 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingstringsrecursion

Last updated

Tests dynamic programming reasoning on sequential digit-to-letter mappings, including careful handling of zeros and invalid two-digit pairs.

Problem

You have a cipher that maps positive integers to letters: 1 → 'a', 2 → 'b', …, 26 → 'z'.

Given a non-empty string s made up of digit characters '0' through '9', return the total number of distinct ways to split s into a sequence of one- or two-digit tokens where each token maps to a valid letter.

A token is valid if:

  • It is a single digit from '1' to '9', or
  • It is a two-digit number from 10 to 26.

The digit '0' can never form a valid token on its own. A two-digit token whose first digit is '0' (such as "05") is also invalid.

If no valid splitting exists, return 0.

Constraints

  • 1 <= len(s) <= 100
  • s consists only of the characters '0'–'9'
  • The answer fits in a 32-bit signed integer for inputs of this length

Examples

Example 1

Input: count_decodings('12')

Output: 2

Example 2

Input: count_decodings('226')

Output: 3

Example 3

Input: count_decodings('06')

Output: 0

Example 4

Input: count_decodings('11106')

Output: 2

Hints

Hint 1

Think about the number of ways to decode the string ending at each position. How does the count at position i relate to the counts at the two positions before it?

Hint 2

There are only two ways the last token of any decoding can look: a single digit, or a two-digit number. Check whether each is valid before adding its contribution.

Hint 3

A lone '0' has no valid single-digit mapping, and a pair like '30' or '00' falls outside the 10–26 range. Once any prefix becomes impossible, the count stays zero for all later positions — no special early-exit is needed for correctness.