Recursion

All Phone Keyboard Interpretations

Backtracking

You received a text message of all numbers. You want to translate this string into letters, and there are many options for doing this. For example, 2 can be interpreted as "a", "b", or "c".

Given the string of numbers 2-9, return all the possible ways you could interpret the text message.

First Few Test Cases:

0. Problem

We'll make a recursive function that visits every possible string we can interpret. It will go through and interpret each number in numbers left to right. This means the function needs to know what index it's up to. It also needs to know the the string of letters it's built so far.

1. Recursion

We want to consider all the possible letters that can be made from the current digit. For every possible digit we can add, we should add it and continue on the next index. Here's the recursion:

2. Base case

When we get to the end of the array, we should add the letters we have to the solution.

3. Code

Here's the full code. Just combine the recursion and the base case, and optimize by using Backtracking, which just means we make all our parameters into global variables.

Time Complexity O(d2d)O(d \cdot 2^d), where dd is the length of numbers. We iterate through each possible string, which roughly 4d4^d entries in the answer. Each entry is of size O(d)O(d). So creating the final output must take d2dd \cdot 2^d time. Another way to think of this is that there are 4d4^d entries we find, and each one spends O(d)O(d) time running "".join(letters).

Space Complexity O(d2d)O(d \cdot 2^d) for the output array. The Call Stack and global parameters also take up some space, but the output array's space complexity beats them by far.

Call Stack Complexity O(d)O(d). The recursion gets up to dd calls deep, and each call uses O(1)O(1) space.

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