Secret Number Notes

Mediumdynamic programmingAlso known as Decode Ways

Two friends pass notes in a simple code: each letter becomes its alphabet position (A is 1, Z is 26), and the numbers are written together with no spaces. "KZ" becomes 1126.

But 1126 could also be "AABF", "ALF" and more. Before guessing, the reader wants to know how many messages a note could mean.

Your task

Write countReadings(note). note is a string of digits. Split it into pieces, each a number from 1 to 26 written without a leading zero, and return how many different splits there are.

So "10" and "20" are valid pieces, but "0", "05" and "27" are not. If the note cannot be split at all, return 0.

countReadings(note: string) → int

Examples

Example 1
Input
note = "1126"
Output
5
Why

The splits are 1-1-2-6 (AABF), 11-2-6 (KBF), 1-12-6 (ALF), 1-1-26 (AAZ) and 11-26 (KZ). 126 is too big, so nothing else works.

Example 2
Input
note = "2105"
Output
1
Why

A 0 cannot stand alone, so it must end a 10 or 20. Here it pairs with the 1, forcing 2-10-5 (BJE). The split 21-0-5 fails on the lone 0.

Constraints

  • 1 ≤ note.length ≤ 60
  • note contains only the digits 0 to 9.
  • The answer is below 10¹³.
Start with brute force

Recursively cut one or two digits off the front, check the piece, and count splits that reach the end. Correct, but a note of sixty 1s has about 2.5 trillion readings, and the recursion walks every one.

Most of that work is repeated. The number of readings of the rest of the note from position 30 is the same however the recursion got there, yet it recomputes that number for every path.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code