Skip to the solution
MediumDSA8 min read

Decode ways DP: how do you handle 0 and 06 edge cases?

612 views

The problem

Question presented to candidate: "A message of letters A to Z was encoded as numbers, A = 1, B = 2, up to Z = 26, and the numbers were written next to each other with no separators. Given the digit string, count how many ways it can be decoded. Pay special attention to zeros โ€” what do you do with a string like '06' or '100'? Code it in Python."

What a strong answer should cover:

  • The state: dp[i] = number of ways to decode the first i digits, with dp[0] = 1 (the empty prefix has one decoding: nothing).
  • The two moves: the last letter used one digit (allowed only if that digit is not 0, add dp[i-1]) or two digits (allowed only if they form 10 to 26, add dp[i-2]).
  • The zero rules: a 0 can never stand alone, so it must be the second digit of 10 or 20; 06 is not a letter because a two-digit code cannot start with 0; 30, 00 or a leading 0 make the whole answer 0.
  • O(n) time and O(1) space with two rolling variables, compared with the exponential plain recursion (the all-1 string grows like Fibonacci).
  • Python details: comparing single characters (s[i - 1] == "2" and s[i] <= "6") instead of int(s[i-1:i+1]) avoids building a slice each step, and int("06") returns 6, which is exactly the bug the question is fishing for.

Clarifying questions expected:

  • Can the string contain zeros, and can it start with one?
  • What should an empty string return?
  • Can the answer be large โ€” should it be returned modulo something?

Code / implementation expected: Yes โ€” a one-pass Python DP with two rolling variables, tested on "06", "10", "100" and "226".

  • dp
  • string
  • Google

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

8 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonDecode ways on the zero edge cases, with every decoding listed
PythonNaive recursion vs DP: call counts and the Fibonacci pattern

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 78 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

What is binary search on the answer?

Continue