Recursion

Number of Interpretations

Dynamic Programming

You're given a string of digits 1-9, called s. You can convert any number into its corresponding letter in the alphabet.

Return the total number of ways you can interpret the given string s as a string of letters.

Example:

s = "123"=> returns 3\notag \def\l#1{& \texttt{#1} } \begin{align*} \l{s = "123"} \\ \l{=> returns 3} \end{align*}

Explanation: The string "123" could be interpreted as the string "abc", since "a" is the number 1, and "b" is the number 2, and "c" is the number 3. The string could also be interpreted as "l\small \tt lc", or as "aw". This is a total of 3 ways to interpret the string.

First Few Test Cases:

0. Problem

We want to find the number of ways to convert the string of numbers into letters.

1. Recursion

To find a recursion, you should focus on the first few letters of the string. Say you're given this string:

To convert the string into letters, you can convert the first number "1" as a letter. You can also consider the first two numbers "12" as a letter. You can then convert the remaining strings into letters. This gives the recursion:

You can generalize this to find a recursion. You need to make sure you only convert numbers "1" through "26" into letters, otherwise you should set the number of ways equal to zero. For example, you cannot convert the string "0" or "34" into a singe letter because they don't correspond to a letter a through z. Here's the recursion for this:

It's better to recurse on numbers than strings:

2. Base case

The recursion calls itself on smaller and smaller strings. In this problem, we need to find two base cases, because the function numWays(i) calls two functions numWays(i+1) and numWays(i+2).

The first base case is that there is 1 way to get to the empty string "":

We also need another base case. The easiest thing to do is just say there are 0 ways to get to i = len(s)+1, because this case is nonsensical so it should be ignored:

3. Code

To code this up, we should use Dynamic Programming and compute all of the function calls in the order that they're needed. We can do this by computing small i first and big i last.

Time Complexity O(n)O(n)

Space Complexity O(n)O(n)

Mark as Completed:
Submits:
numInterpretations
Test your code to get an output here!
numInterpretations(
)
Test your code to get an output here!