Count possible decoding of a given digit sequence
Learn how to solve the 'Count possible decoding of a given digit sequence' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
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.
- •1 <= len(digits) <= 20
- •digits contains only characters '0' through '9'
Examples
count_decodings('12')2
'12' can be decoded as 'AB' (1,2) or 'L' (12). So 2 ways.
count_decodings('226')3
'226' can be decoded as 'BBF' (2,2,6), 'BZ' (2,26), or 'VF' (22,6). So 3 ways.
count_decodings('06')0
'06' cannot be decoded because '0' has no letter mapping and '06' is not a valid code.
Need a Hint?
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.