← Questions
Decode ways: count letter decodings of a digit string
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A message of letters was encoded as digits with A -> 1, B -> 2, …, Z -> 26, with no separators. Given the digit string, return how many different letter messages it could decode to.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
num_decodings(s: str) -> int— every group must be1–26with no leading zero, so"06"is not a valid group.
Example
num_decodings("12") -> 2 # "AB" or "L"
num_decodings("226") -> 3 # "BZ", "VF", "BBF"
num_decodings("06") -> 0 # a group cannot start with 0
num_decodings("11106") -> 2 # "AAJF" or "KJF"
num_decodings("2101") -> 1 # only 2|10|1 = "BJA"; "01" is not a group
Constraints
-
1 <= len(s) <= 100,sholds digits only. - The answer fits in a 32-bit integer.
Clarifying questions
- What should an empty string return?
- Can the string contain characters other than digits?
- Should I return the count only, or also the decodings?
- If the answer can be huge, should it be returned modulo some number?
What a strong answer covers
- The recurrence:
ways[i] = ways[i-1]if digitiis1–9, plusways[i-2]if the last two digits form10–26. - O(n) time and O(1) space by keeping only the last two values.
- Zeros: a
0must pair with a1or2before it, so"30"and"100"give 0. - Why plain recursion is exponential and how memoization fixes it.
- Tests:
"0","10","27","101", a long run of1s.
Follow-ups
- Return every decoding, not just the count.
- A
*can stand for any digit1–9. Count the decodings modulo 10^9 + 7. - The mapping is a given table of codes of any length. Generalize the DP.
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
