Secret Number Notes

Mediumdynamic programmingAlso known as Decode Ways

Two friends pass notes in class using a simple code: every letter becomes its position in the alphabet, so A is 1, B is 2, and Z is 26. To make the notes harder to read, they write all the numbers together with no spaces. "KZ" becomes 1126.

The trouble is that 1126 could also be "AABF", "ALF" and a few more. Before guessing, the reader wants to know how many different messages a note could mean.

Your task

Write countReadings(note). note is a string of digits. Split it into pieces, where each piece is 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). The piece 126 is too big, so nothing else works.

Example 2
Input
note = "2105"
Output
1
Why

A 0 can never stand alone, so it must be the end of 10 or 20. Here it pairs with the 1 to make 10, which forces 2-10-5 (BJE). The split 21-0-5 fails because of 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 off one or two digits from the front, check the piece is valid, and count the splits that reach the end. It is correct, but a note of sixty 1s has about 2.5 trillion readings, and the recursion walks through every one.

The waste: the number of readings of "the rest of the note from position 30" is the same no matter how you got there, yet the recursion recomputes it for every path that reaches position 30.

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