Search⌘ K
AI Features

Decode Ways

Understand how to decode digit-only strings into possible alphabet sequences by applying dynamic programming. Learn to count all valid interpretations using memoization or tabulation, a common interview problem pattern in coding challenges.

Statement

Given a string that has only positive digits, your task is to decode the string and determine the number of possible ways to decode it.

Consider the input string as an encoded message, where each digit in the string represents an alphabet from A to Z. For reference, let’s look at the mapping below:

"1" represents "A"

"2" represents "B"

"3" represents "C"

\dots

"26" represents "Z"

How to perform the decode operation?

To decode an encoded message, we have to check whether or not each digit in the string can be mapped onto the mapping above. There can be multiple ways to decode a string.

For example, the string "231012" can be decoded in the following ways:

  • Option 1 \rightarrow "2", "3", "10", "1", "2" \rightarrow "B", "C", "J", "A", "B"

  • Option 2 \rightarrow "2", "3", "10", "12" \rightarrow "B", "C", "J", "L"

  • Option 3 \rightarrow "23", "10", "1", "2" \rightarrow "W", "J", "A", "B"

  • Option 4 \rightarrow "23", "10", "12" \rightarrow "W", "J", "L"

Note: In the mapping above, we haven't included "01" since it's an invalid mapping. It cannot be mapped onto "A" since "01" and "1" are different.

Constraints:

  • 11 \leq decodeStr.length 100\leq 100

  • The string decodeStr contains only digits and may contain leading zero(s).

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Decode Ways

1.

What is the output if the following string is given as input?

“1111”

A.

4

B.

6

C.

5


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in the following coding playground.

Java
usercode > Main.java
import java.util.*;
public class Main {
public static int numOfDecodings(String decodeStr) {
// Replace this placeholder return statement with your code
return 1;
}
}
Decode Ways