Zepruv › Coding problems

Decode Ways

Medium · String, 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:
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

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

Example 2

Input: s = "226"
Output: 3

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

Example 3

Input: s = "06"
Output: 0

"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

Starter code (python)

class Solution(object):
    def numDecodings(self, s):
        """
        :type s: str
        :rtype: int
        """
        

Related problems

Previous: Subsets II · Next: Reverse Linked List II · All problems

Zepruv is a technical interview practice platform. Read any problem for free; sign in to run your code, submit and keep your progress.