DYNP-P3

Ways to decode

Practice 3 of 9Dynamic programming11 tests

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

  • s has 1 to 100,000 digits.
  • Python stops at about 1,000 nested calls, and a function wrapped in functools.cache stops 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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

11 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2Two digitsNot run
3Only a zeroNot run
4TenNot run
5Two zerosNot run
6Too big to pairNot run
7A leading zeroNot run
8Zeros insideNot run
9Forty onesNot run
10100,000 digitsNot run
11A bad zero near the endNot run