medium Decode Ways
Problem Statement
You have given a string that consists only of digits. This string can be decoded into a set of alphabets where '1' can be represented as 'A', '2' as 'B', ... , '26' as 'Z'. The task is to determine how many ways the given digit string can be decoded into alphabets.
Examples
-
- Input: "121"
- Expected Output: 3
- Justification: The string "121" can be decoded as "ABA", "AU", and "LA".
-
- Input: "27"
- Expected Output: 1
- Justification: The string "27" can only be decoded as "BG".
-
- Input: "110"
- Expected Output: 1
- Justification: The string "110" can only be decoded as "JA".
Constraints:
1 <= s.length <= 100scontains only digits and may contain leading zero(s).
Try it yourself
Try solving this question here:
✅ Solution Decode Ways
Problem Statement
You have given a string that consists only of digits. This string can be decoded into a set of alphabets where '1' can be represented as 'A', '2' as 'B', ... , '26' as 'Z'. The task is to determine how many ways the given digit string can be decoded into alphabets.
Examples
-
- Input: "121"
- Expected Output: 3
- Justification: The string "121" can be decoded as "ABA", "AU", and "LA".
-
- Input: "27"
- Expected Output: 1
- Justification: The string "27" can only be decoded as "BG".
-
- Input: "110"
- Expected Output: 1
- Justification: The string "110" can only be decoded as "JA".
Constraints:
1 <= s.length <= 100scontains only digits and may contain leading zero(s).
Solution
Our approach to solving this problem involves using dynamic programming to iteratively build the solution. Given a string of digits, we want to determine how many ways it can be decoded into alphabets. The key insight is that the number of ways to decode a string of length i is dependent on the number of ways to decode the previous two substrings of length i-1 and i-2. We'll use two variables, prev and current, to store these values and update them as we loop through the string.
-
Initialization: Begin by checking if the string is valid for decoding (e.g., it should not start with a '0'). If the string is invalid, return 0. Next, initialize two variables,
prevandcurrent, both set to 1.prevwill store the number of ways to decode the string of lengthi-2, andcurrentwill store the number of ways to decode the string of lengthi-1. -
Iterate Through the String: Loop through the string from the second character to the end. For each character, compute the number of ways it can be decoded when combined with the previous character.
-
Update Variables: For each character, evaluate the following conditions:
- If the current character and the previous character form a valid number between 10 and 26, they can be decoded together.
- If the current character is not '0', it can be decoded individually.
Use these conditions to update the
prevandcurrentvariables accordingly.
-
Return the Result: Once the iteration completes, the
currentvariable will hold the total number of ways the entire string can be decoded. Return this value.
This dynamic programming approach is efficient because it computes the solution by using previously calculated results, and it avoids redundant calculations. By tracking and updating the number of ways to decode the current and previous substrings, the algorithm effectively builds the solution for the entire string.
Algorithm Walkthrough
Consider the input "121":
- Initialize
prev = 1andcurrent = 1. - For the second character '2':
- "12" can be decoded as "AB" or "L".
- Update
prevandcurrentby swapping their values and settingcurrent += prev. - Now,
prev = 1andcurrent = 2.
- For the third character '1':
- "21" can be decoded as "BA" or "U".
- Again, update
prevandcurrent. - Now,
prev = 2andcurrent = 3.
- The final answer is 3, which is the value of
current.
Code
class Solution {
public int numDecodings(String s) {
// Return 0 for empty strings or strings starting with '0'
if (s == null || s.length() == 0 || s.charAt(0) == '0') {
return 0;
}
// Initialize two variables to store results of sub-problems
int prev = 1, current = 1;
for (int i = 1; i < s.length(); i++) {
int temp = 0;
// If current character is not '0', it can be decoded on its own
if (s.charAt(i) != '0') {
temp = current;
}
// Check if two characters can be decoded together
int twoDigits = Integer.parseInt(s.substring(i - 1, i + 1));
if (twoDigits >= 10 && twoDigits <= 26) {
temp += prev;
}
prev = current;
current = temp;
}
return current;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.numDecodings("121")); // Expected 3
System.out.println(sol.numDecodings("27")); // Expected 1
System.out.println(sol.numDecodings("110")); // Expected 1
}
}
Complexity Analysis
-
Time Complexity: O(N), where N is the length of the string. We loop through the string once.
-
Space Complexity: O(1), as we only use a constant amount of space regardless of the input size.
🤖 Don't fully get this? Learn it with Claude
Stuck on Decode Ways? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Decode Ways** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Decode Ways** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Decode Ways**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Decode Ways**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.