The problem
A message of capital letters was turned into digits with A = 1, B = 2, …, Z = 26, and the numbers were written one after another with no spaces. Given the digits s, return the number of different ways to read them as letters.
decode_ways("226") # 3: 2 2 6, 22 6, 2 26
decode_ways("10") # 1: only 10 (J)
decode_ways("06") # 0: 06 is not a letter
- A letter is 1 to 9 (one digit) or 10 to 26 (two digits). A 0 can only be the second digit of 10 or 20.
- The count can have thousands of digits. Return the remainder after dividing it by 1,000,000,007:
count % 1_000_000_007. You may take the remainder after every addition; the result is the same.
Limits
shas 1 to 100,000 digits.- Python stops at about 1,000 nested calls, and a function wrapped in
functools.cachestops after a few hundred in the browser. The big tests need far more than that, so memoised recursion fails them. Fill a table with a loop (lesson 3).
Builds on DYNP-3 Tabulation.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
11 tests, not run yet
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | Two digits | Not run | |
| 3 | Only a zero | Not run | |
| 4 | Ten | Not run | |
| 5 | Two zeros | Not run | |
| 6 | Too big to pair | Not run | |
| 7 | A leading zero | Not run | |
| 8 | Zeros inside | Not run | |
| 9 | Forty ones | Not run | |
| 10 | 100,000 digits | Not run | |
| 11 | A bad zero near the end | Not run |