Taro Logo

Decode Ways

#74 Most AskedMedium
0 views
Topics:
Dynamic Programming

You have intercepted a secret message encoded as a string of numbers. The message is decoded via the following mapping:

"1" -> 'A'
"2" -> 'B'
...
"25" -> 'Y'
"26" -> 'Z'

However, while decoding the message, you realize that there are many different ways you can decode the message because some codes are contained in other codes ("2" and "5" vs "25").

For example, "11106" can be decoded into:

  • "AAJF" with the grouping (1, 1, 10, 6)
  • "KJF" with the grouping (11, 10, 6)
  • The grouping (1, 11, 06) is invalid because "06" is not a valid code (only "6" is valid).

Note: there may be strings that are impossible to decode.

Given a string s containing only digits, return the number of ways to decode it. If the entire string cannot be decoded in any valid way, return 0.

The test cases are generated so that the answer fits in a 32-bit integer.

Example 1:

Input: s = "12"

Output: 2

Explanation:

"12" could be decoded as "AB" (1 2) or "L" (12).

Example 2:

Input: s = "226"

Output: 3

Explanation:

"226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

Example 3:

Input: s = "06"

Output: 0

Explanation:

"06" cannot be mapped to "F" because of the leading zero ("6" is different from "06"). In this case, the string is not a valid encoding, so return 0.

Constraints:

  • 1 <= s.length <= 100
  • s contains only digits and may contain leading zero(s).

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if the input string is empty, null, or contains non-digit characters?
  2. How should we handle leading zeros (e.g., "0" or "06"), since they do not map to any valid letter?
  3. Can numbers like "10" or "20" only be decoded as 'J' and 'T' respectively, or can they also be split into 'A' and 'F'/'J'?
  4. Is the input string guaranteed to contain only numeric digits, or could it potentially exceed standard integer limits in length?
  5. If the string cannot be decoded at all, should we return 0?

Brute Force Solution

Approach

Imagine you have a secret message made of numbers where each letter of the alphabet is represented by a number from one to twenty-six, and your job is to find every single possible way to spell out words using that number string. The brute force approach works by trying out every possible path of translating the numbers into letters from start to finish.

Here's how the algorithm would work step-by-step:

  1. Start at the very beginning of the string of numbers.
  2. Look at the first number by itself and see if it can represent a valid letter, and if so, imagine moving forward to translate the rest of the message.
  3. Next, look at the first two numbers together and see if they combine to represent a valid letter between ten and twenty-six, and if so, imagine moving forward from there as well.
  4. Whenever you make a choice to take either one number or two numbers, follow that path all the way to the end of the message.
  5. If at any point you hit an invalid number combination, like a zero that cannot be matched properly, stop following that path because it is a dead end.
  6. If you successfully reach the very end of the message by translating every single number, count that as one complete and valid way to decode the message.
  7. Repeat this exploration for every single branch of choices from the very beginning to the very end, and finally tally up all the successful ways you discovered.

Code Implementation

Big(O) Analysis

Time Complexity
O(2ⁿ) – At each position in the string of length n, the recursive approach makes up to two choices by considering either a single digit or a pair of digits. Exploring these branching paths for every single number creates a binary decision tree of depth n. Since the number of paths doubles roughly at each step, this results in approximately 2ⁿ total operations, which simplifies to O(2ⁿ).
Space Complexity
O(N) – The space complexity is driven by the recursive exploration of paths from the beginning to the end of the string. As the algorithm follows branch after branch of choices, the recursive call stack grows to a maximum depth of N, where N is the length of the message string. Additionally, if the approach is optimized by storing intermediate results to avoid redundant calculations, a memoization table or auxiliary DP array of size N is used. Therefore, the total extra memory scales directly with the length of the input, simplifying to Big O of N.

Optimal Solution

Approach

Instead of exploring every possible secret message translation at once, the optimal approach works backward from the end of the message to calculate the total number of valid ways piece by piece. By remembering the results of previous translations as we move along, we avoid repeating work and instantly figure out how many combinations are possible.

Here's how the algorithm would work step-by-step:

  1. Look at the very end of the secret message to see how many valid ways exist to translate the final part.
  2. Step backward one character at a time, checking whether the current character alone can form a valid letter.
  3. Check if the current character combined with the one immediately following it can form a valid two-character letter.
  4. Combine the valid translation counts from these checks to figure out the total number of ways to translate the message up to this point.
  5. Keep a running tally of these valid translation counts as you continue moving toward the beginning of the message.
  6. Reach the very beginning of the message to reveal the final total number of possible ways the whole message can be decoded.

Code Implementation

def num_decodings(secret_message):    message_length = len(secret_message)        ways_from_end = [0] * (message_length + 1)        ways_from_end[message_length] = 1    # Working backward avoids redundant calculations by storing previous translation results.    for current_index in range(message_length - 1, -1, -1):        if secret_message[current_index] == '0':            ways_from_end[current_index] = 0                    else:            ways_from_end[current_index] = ways_from_end[current_index + 1]                        # Combining two characters is valid only when the resulting number falls between 10 and 26.            if current_index + 1 < message_length:                two_digit_prefix = secret_message[current_index : current_index + 2]                                if '10' <= two_digit_prefix <= '26':                    ways_from_end[current_index] += ways_from_end[current_index + 2]    # Reaching the beginning accumulates all valid paths into the final total combination count.    return ways_from_end[0]

Big(O) Analysis

Time Complexity
O(n) – To decode the message, we iterate backward from the end of the string to the very beginning, processing each character exactly once. At each step, we perform a constant number of operations by checking the current single character and the two-character combination immediately following it. Since we visit all n characters in the message in a single pass without any nested loops, the total number of operations scales linearly with the input size. This direct one-pass traversal simplifies to an optimal time complexity of O(n).
Space Complexity
O(1) – The algorithm tracks translation counts by maintaining a few primitive variables representing the results of the immediately preceding steps rather than using an auxiliary array of size N. As we step backward through the message, only these constant scalar values are updated in place to maintain the running tally. Because the extra memory required does not grow with the length of the input string, the auxiliary space complexity remains strictly constant.

Edge Cases

String starting with the character zero
How to Handle:
The dp state for this index must be zero because no valid letter maps to a standalone zero.
String containing consecutive zeros like double zero
How to Handle:
Invalid two-digit combinations will yield zero ways, halting the propagation of valid decodings.
Single-digit valid string such as a string containing only five
How to Handle:
Base cases correctly initialize the dynamic programming array to return one valid decoding way.
Two-digit number greater than twenty-six such as fifty-six
How to Handle:
The algorithm checks the numerical range and only adds the two-digit decode path if it falls between ten and twenty-six.
Two-digit number ending in zero such as ten or twenty
How to Handle:
The algorithm must correctly recognize these as valid single two-digit decodings while preventing invalid single-digit parses of the zero.
Long strings with maximum constraints
How to Handle:
Using an iterative dynamic programming approach with constant space ensures optimal performance and prevents stack overflow.
Inputs with no valid decoding path whatsoever
How to Handle:
The DP state naturally accumulates a final result of zero, correctly indicating that no valid decoding exists.
0/257 completed