Program to find number of ways we can decode a message in Python

Suppose we have a mapping like a = 1, b = 2, ... z = 26, and we have an encoded message string. We need to count the number of ways it can be decoded using dynamic programming.

For example, if the input is message = "222", then the output will be 3, as this can be decoded in 3 ways: "bbb" (2-2-2), "bv" (2-22), and "vb" (22-2).

Algorithm

To solve this problem, we will follow these steps ?

  • Create a memo array of size message length + 1 initialized with zeros

  • Set memo[0] = 1 (base case for empty string)

  • Set memo[1] = 1 if first character is not "0", otherwise 0

  • For each position i from 2 to message length:

    • Check single digit: if message[i-1] is valid (1-9), add memo[i-1]

    • Check two digits: if message[i-2:i] is valid (10-26), add memo[i-2]

  • Return the last element of memo array

Example

Let's implement this solution using dynamic programming ?

class Solution:
    def solve(self, message):
        memo = [0 for i in range(len(message) + 1)]
        memo[0] = 1
        memo[1] = 1 if message[0] != "0" else 0
        
        for i in range(2, len(message) + 1):
            n1 = int(message[i-1:i])
            n2 = int(message[i-2:i])
            
            n1_valid = n1 > 0
            n2_valid = n2 > 9 and n2 < 27
            
            if n1_valid:
                memo[i] += memo[i-1]
            if n2_valid:
                memo[i] += memo[i-2]
        
        return memo[-1]

ob = Solution()
message = "2223"
print(f"Number of ways to decode '{message}': {ob.solve(message)}")

The output of the above code is ?

Number of ways to decode '2223': 5

How It Works

For the input "2223", the possible decodings are:

  • 2-2-2-3 ? "bbbc"

  • 22-2-3 ? "vbc"

  • 2-22-3 ? "bvc"

  • 2-2-23 ? "bbw"

  • 22-23 ? "vw"

The dynamic programming approach builds up solutions by considering whether we can form valid single or double-digit numbers at each position.

Conclusion

This dynamic programming solution efficiently counts message decoding ways in O(n) time. The key insight is that each position depends on whether single or double-digit combinations form valid letter mappings.

Updated on: 2026-03-25T10:59:41+05:30

415 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements