CodeArchon

medium1-D Dynamic ProgrammingFacebookAmazonMicrosoft

Numeric Decoder

A spy maps 1→A, 2→B, …, 26→Z and counts the number of distinct letter sequences a digit string could decode to.

Given a numeric string using digits 1-9 and possibly 0, return the number of ways to decode it (A=1,...,Z=26).

Choose approach

1
0
1
1
?
2
?
3
i
1/3
Narrationstep 1 of 3

Seed dp[0]=dp[1]=1.

1def numDecodings(s):
2 n = len(s)
3 if not n or s[0] == '0': return 0
4 dp = [0]*(n+1); dp[0] = dp[1] = 1
5 for i in range(2, n+1):
6 if s[i-1] != '0': dp[i] += dp[i-1]
7 two = int(s[i-2:i])
8 if 10 <= two <= 26: dp[i] += dp[i-2]
9 return dp[n]
Variables

How to think about it

  1. Each position is reached from previous OR two-back if last two digits form 10..26.
  2. Leading '0' kills a branch.

Edge cases to catch in interview

  • "0" -> 0.
  • "06" -> 0 (no leading zero decode).

Examples

Example 12
{"s":"12"}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed