← Back to Codes

2026-06-09 16:36:42

Decode Ways in Python and Java | LeetCode #91

Learn how to solve Decode Ways in Python and Java with beginner-friendly explanation, step-by-step dry run, custom examples, and time complexity.

Decode Ways in Python and Java

In this tutorial, we will learn LeetCode #91: Decode Ways in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.

What Is the Decode Ways Problem?

This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.

For this problem, we will use dynamic programming because it gives a clean and optimized solution.

Example input:
s = "2263"

Expected result:
Output: 3

Explanation:
Valid decodings include 2-2-6-3, 22-6-3, 2-26-3.

Beginner-Friendly Idea

The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.

At each step, ask: “What do I already know, and how does the current value change my answer?”

Using our example:
s = "2263"

Approach:
dynamic programming

We update variables step by step until we reach:
Output: 3

Why Do We Use This Approach?

A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.

That is why dynamic programming is useful for this problem.

Step-by-Step Explanation

Let us dry run the algorithm using a custom example.

Step 1
Use this custom example.

s = "2263"

We will solve it using dynamic programming.

Step 2
Look at the first important value from the example and create the variables needed by the algorithm.

current_state = based on the first value
answer = not finished yet

Step 3
Move to the next useful value and update the state.

The algorithm compares the new value with the old state.
If the new value improves the answer, we update the answer.

Step 4
Continue this process until all useful values are processed.

After processing the example, we get:

Output: 3

Why?
Valid decodings include 2-2-6-3, 22-6-3, 2-26-3.

Important Code Logic

The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.

Think like this:

old_state = what we knew before
current_value = value we are checking now
new_state = updated result after using current_value

For our example, the final state gives:
Output: 3

Example 1

Input:
s = "2263"

Output:
Output: 3

Explanation:
Valid decodings include 2-2-6-3, 22-6-3, 2-26-3.

Example 2

Input:
s = "1212"

Output:
5

Explanation:
The string has multiple valid decoding combinations.

Python Code

Here is the complete Python solution for LeetCode #91.

class DecodeWaysCounter:
    def num_decodings(self, s):
        if not s or s[0] == "0":
            return 0

        two_back = 1
        one_back = 1

        for i in range(1, len(s)):
            current = 0

            if s[i] != "0":
                current += one_back

            two_digit = int(s[i - 1:i + 1])
            if 10 <= two_digit <= 26:
                current += two_back

            two_back = one_back
            one_back = current

        return one_back


counter = DecodeWaysCounter()
print(counter.num_decodings("2263"))  # Output: 3
print(counter.num_decodings("101"))   # Output: 1

Java Code

Here is the complete Java solution for LeetCode #91.

class DecodeWaysCounter {
    public int numDecodings(String s) {
        if (s.length() == 0 || s.charAt(0) == '0') {
            return 0;
        }

        int twoBack = 1;
        int oneBack = 1;

        for (int i = 1; i < s.length(); i++) {
            int current = 0;

            if (s.charAt(i) != '0') {
                current += oneBack;
            }

            int twoDigit = Integer.parseInt(s.substring(i - 1, i + 1));
            if (twoDigit >= 10 && twoDigit <= 26) {
                current += twoBack;
            }

            twoBack = oneBack;
            oneBack = current;
        }

        return oneBack;
    }

    public static void main(String[] args) {
        DecodeWaysCounter counter = new DecodeWaysCounter();
        System.out.println(counter.numDecodings("2263")); // Output: 3
        System.out.println(counter.numDecodings("101"));  // Output: 1
    }
}

Time and Space Complexity

Time Complexity: O(n)

The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.

Space Complexity: O(n)

The extra space is used for the variables or data structures needed by the optimized approach.

Final Summary

LeetCode #91: Decode Ways becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.