Python BasicsEasy

Count possible decoding of a given digit sequence

Detailed guide and Python implementation for the 'Count possible decoding of a given digit sequence' problem.

Problem Statement

Easy

Write a function count_decodings(digits) that takes a string of digits and returns the number of possible ways to decode it, where 'A' = 1, 'B' = 2, ..., 'Z' = 26.

For example, '12' can be decoded as 'AB' (1, 2) or 'L' (12), giving 2 ways.

If the string contains '0' in an invalid position (e.g., leading '0' or '30'), those paths are invalid and should not be counted.

Constraints
  • 1 <= len(digits) <= 20
  • digits contains only characters '0' through '9'

Examples

Example 1
Input
count_decodings('12')
Output
2
Explanation

'12' can be decoded as 'AB' (1,2) or 'L' (12). So 2 ways.

Example 2
Input
count_decodings('226')
Output
3
Explanation

'226' can be decoded as 'BBF' (2,2,6), 'BZ' (2,26), or 'VF' (22,6). So 3 ways.

Example 3
Input
count_decodings('06')
Output
0
Explanation

'06' cannot be decoded because '0' has no letter mapping and '06' is not a valid code.

Need a Hint?
Consider using Numbers-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.