Practice
Data Structures and Algorithms
Machine Coding Round (LLD)
System Design & Architecture (HLD)
Frontend UI Machine Coding
Resources
Career Advice and Roadmaps
Data Structures and Algorithms
Machine Coding Round (LLD)
System Design & Architecture (HLD)
Backend Development
Frontend Development
Project Ideas for Software Developers
Core Computer Science
Companies
SDE Jobs & Internships
Interview Questions
Compare Companies
IDE
Online IDE
Collaborative IDE

Decode Ways Editorial

DSA Editorial, Solution and Code

Practice Problem Link: Decode Ways

Please make sure to try solving the problem yourself before looking at the editorial.

Problem Statement

A message containing letters from 'A' to 'Z' is being encoded into numbers using the following encoding:

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

Given an encoded string, find the number of ways it can be decoded.

Naive Approach

A simple solution is to recursively try every possible combination of single-digit numbers and two-digit numbers less than 27 and keep the count of valid combinations.

Analysis

  • Time Complexity: Exponential
  • Auxiliary Space Complexity: O(1)

Implementation

C++
int mod = 1000000007;
int countWays(string str, int start, int end) {
	if(start > end || (start == end && str[start] != '0')) {
		return 1;
	} 
	if (str[start] == '0') {
		return 0;
	}
	int ways = 0;
	ways = (ways + countWays(str, start + 1, end)) % mod;
	if (start < end && (str[start] == '1' || str[start] <= '2' && str[start + 1] <= '6') ){
		ways = (ways + countWays(str, start + 2, end)) % mod;
	} 
	return ways;
}
int numDecodings(string str) {
	int start = 0;
    return countWays(str, start, str.size() - 1);
}
Java
class Solution {
	int mod = 1000000007;
	int countWays(String str, int start, int end) {
		if(start > end || (start == end && str.charAt(start) != '0')) {
			return 1;
		} 
		if (str.charAt(start) == '0') {
			return 0;
		}
		int ways = 0;
		ways = (ways + countWays(str, start + 1, end)) % mod;
		if (start < end && (str.charAt(start) == '1' || str.charAt(start) <= '2' && str.charAt(start + 1) <= '6') ){
			ways = (ways + countWays(str, start + 2, end)) % mod;
		} 
		return ways;
	}
	int numDecodings(String str) {
	    int start = 0;
  	    return countWays(str, start, str.length() - 1);
	}
}

Optimal Approach (Memoization)

The idea is similar to the naive solution but to avoid multiple computations for each index, we can memoize the subproblems so that the result of overlapping intervals can be computed in constant time.

Analysis

  • Time Complexity: O(n)
  • Auxiliary Space Complexity: O(n)

Implementation

C++
int mod = 1000000007;
unordered_map<int, int> memoize;
int countWays(string str, int start, int end) {
	if(start > end || (start == end && str[start] != '0')) {
		return 1;
	} 
	if (str[start] == '0') {
		return 0;
	}
	if(memoize.find(start) != memoize.end()) {
		return memoize[start];
	}
	int ways = 0;
	ways = (ways + countWays(str, start + 1, end)) % mod;
	if (start < end && (str[start] == '1' || str[start] <= '2' && str[start + 1] <= '6') ){
		ways = (ways + countWays(str, start + 2, end)) % mod;
	} 
	memoize[start] = ways;
	return ways;
}
int numDecodings(string str) {
	memoize.clear();
    return countWays(str, 0, str.size() - 1);
}
Java
class Solution {
	int mod = 1000000007;
	HashMap<Integer, Integer> memoize = new HashMap<Integer, Integer>();
	int countWays(String str, int start, int end) {
		if(start > end || (start == end && str.charAt(start) != '0')) {
			return 1;
		} 
		if (str.charAt(start) == '0') {
			return 0;
		}
		if(memoize.containsKey(start)) {
			return memoize.get(start);
		}
		int ways = 0;
		ways = (ways + countWays(str, start + 1, end)) % mod;
		if (start < end && (str.charAt(start) == '1' || str.charAt(start) <= '2' && str.charAt(start + 1) <= '6') ){
			ways = (ways + countWays(str, start + 2, end)) % mod;
		} 
		memoize.put(start, ways);
		return ways;
	}
	int numDecodings(String str) {
	    memoize.clear();
    	return countWays(str, 0, str.length() - 1);
	}
}

Optimal Approach (Bottom-Up)

The optimal approach is based on dynamic programming. For every index i, the number of valid combinations up to ith index depends upon the number of valid combinations up to (i - 2)th index and (i - 1)th index.

Analysis

  • Time Complexity: O(n)
  • Auxiliary Space Complexity: O(n)

Implementation

C++
int mod = 1000000007;
int numDecodings(string str) {
	if (str[0] == '0') {
		return 0;
	}
    int n = str.size();
	int currWays[n + 1] = {0};
	currWays[0] = 1;
	currWays[1] = 1;
	for (int i = 2; i <= n; i++) {
		if (str[i - 1] > '0') {
			currWays[i] = currWays[i - 1];
		}
		if (str[i - 2] == '1' || (str[i - 2] == '2' && str[i - 1] <= '6')) {
			currWays[i] = (currWays[i] + currWays[i - 2]) % mod;
		}
	}
	return currWays[n];
}
Java
class Solution {
	int mod = 1000000007;
	int numDecodings(String str) {
	    if (str.charAt(0) == '0') {
			return 0;
		}
		int n = str.length();
		int[] currWays = new int[n + 1];
		currWays[0] = 1;
		currWays[1] = 1;
		for (int i = 2; i <= n; i++) {
			if (str.charAt(i - 1) > '0') {
				currWays[i] = currWays[i - 1];
			}
			if (str.charAt(i - 2) == '1' || (str.charAt(i - 2) == '2' && str.charAt(i - 1) <= '6')) {
				currWays[i] = (currWays[i] + currWays[i - 2]) % mod;
			}
		}
		return currWays[n];
	}
}
Related Content
Best Time to Buy and Sell Stocks
Best Time to Buy and Sell Stocks II
Best Time to Buy and Sell Stock III
Best Time to Buy and Sell Stock IV
Climbing Stairs
Coin Change
Collect Jewels
Edit Distance (Levenshtein Distance)
Minimum Egg Drops
Longest Common Subsequence (LCS)
Longest Increasing Subsequence (LIS)
Longest Palindromic Substring (LPS)
Maximum path sum in matrix
Maximum Product Subarray
Maximum Sum Increasing Subsequence
Palindrome Partitioning
Palindrome Partitioning 2
Regular Expression Matching
Rod Cutting
Subset Sum
Subset Sum 2
Trapping Rain Water
Unique Paths
Wildcard Matching
Word Break
Word Break - II
SDE Bootcamp - Become a software engineer at a product-based company
Practice Data Structures & Algorithms
Learning Resources
Interview Prep Resources
Community
Join our community
Blog
  • Career Advice and Roadmaps
  • Data Structures & Algorithms
  • Machine Coding Round (LLD)
  • System Design & Architecture
  • Backend Development
  • Frontend Development
  • Awesome Project Ideas
  • Core Computer Science
Practice Questions
  • Machine Coding (LLD) Questions
  • System Design (HLD) Questions
  • Topic-wise DSA Questions
  • Company-wise DSA Questions
  • DSA Sheets (Curated Lists)
  • JavaScript Interview Questions
  • Frontend UI Machine Coding Questions
Online Compilers (IDE)
  • Online Java Compiler
  • Online C++ Compiler
  • Online C Compiler
  • Online Python Compiler
  • Online JavaScript Compiler
Topic-wise Problems
  • Dynamic Programming Interview Questions
  • Linked List Interview Questions
  • Graph Interview Questions
  • Backtracking Interview Questions
  • Arrays Interview Questions
  • Trees Interview Questions
Company-wise Problems
  • Amazon Interview Questions
  • Microsoft Interview Questions
  • Google Interview Questions
  • Flipkart Interview Questions
  • Adobe Interview Questions
  • Facebook Interview Questions
DSA Sheets (Curated Lists)
  • Top Interview Questions
  • FAANG Interview Questions
  • Most Asked Interview Questions
  • 6 month DSA Practice Sheet
  • 3 month DSA Practice Sheet
  • Last minute DSA Practice Sheet