Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Count decode ways

Count the number of ways to decode a digit string where '1'->'A' ... '26'->'Z' using dynamic programming.

Python practice16 minDynamic ProgrammingIntermediateLast updated March 29, 2026

Problem statement

Given a string s containing only digits, return the number of ways to decode it to letters where '1' maps to 'A', '2' to 'B', ..., '26' to 'Z'. A '0' cannot be decoded alone and must be part of a valid '10' or '20' pair. Use dynamic programming to count possible decodings.

Task

Use DP to count valid decodings of a numeric string, handling zeros and two-digit valid pairs.

Examples

Two ways

Input

num_decodings('12')

Output

2

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

Input format

Function num_decodings(s: str) -> int

Output format

Return an integer count of valid decodings.

Constraints

0 <= len(s) <= 1000. s contains only numeric characters '0'..'9'. Leading zeros or invalid pairs should produce zero valid decodings.

Samples

Sample 1

Input

num_decodings('226')

Output

3

'226' -> 'BZ' (2,26), 'VF' (22,6), 'BBF' (2,2,6)