Practice › Dynamic Programming
Decode Ways
Medium · Dynamic Programming · Asked at Amazon, Meta, Google, Microsoft, Uber
Letters are encoded as numbers: A = 1, B = 2, …, Z = 26. Given a string of digits, count the ways to decode it back into letters (every digit must be used, and a group like 06 is not valid). Print the count modulo 10^9 + 7.
Input
A single line with the digit string.
Output
The number of decodings modulo 10^9 + 7 (0 if there is none).
Constraints
- 1 ≤ length ≤ 10^5
dp[i] = ways to decode the first i digits. Add dp[i − 1] if digit i is 1–9, and dp[i − 2] if the last two digits form 10–26.
Example 1
Input
226
Output
3
Example 2
Input
06
Output
0
Hints
- The last letter of a decoding uses either the last digit or the last two digits.
- One digit works if it is 1–9; two digits work if they form 10–26 (no leading zero).
- dp[i] = (one-digit case ? dp[i − 1] : 0) + (two-digit case ? dp[i − 2] : 0).
Approach
dp[0] = 1 (empty prefix) and dp[1] = 1 unless the first digit is 0. For each next position add dp[i − 1] when s[i − 1] ≠ '0', and dp[i − 2] when s[i − 2..i − 1] is between 10 and 26. Keep only the last two values and reduce modulo 10^9 + 7, since the count grows like Fibonacci.
Complexity: O(n) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
const long long MOD = 1000000007LL;
string s;
cin >> s;
long long a = 1, b = (s[0] != '0');
for (size_t i = 2; i <= s.size(); i++) {
long long c = 0;
if (s[i - 1] != '0') c = b;
int two = (s[i - 2] - '0') * 10 + (s[i - 1] - '0');
if (s[i - 2] != '0' && two <= 26) c = (c + a) % MOD;
a = b;
b = c;
}
cout << b << "\n";
return 0;
}Python solution
MOD = 10**9 + 7
s = input().strip()
a, b = 1, (1 if s[0] != "0" else 0)
for i in range(2, len(s) + 1):
c = b if s[i - 1] != "0" else 0
if s[i - 2] != "0" and int(s[i - 2 : i]) <= 26:
c = (c + a) % MOD
a, b = b, c
print(b)Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
final long MOD = 1000000007L;
String s = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
long a = 1, b = s.charAt(0) != '0' ? 1 : 0;
for (int i = 2; i <= s.length(); i++) {
long c = s.charAt(i - 1) != '0' ? b : 0;
int two = (s.charAt(i - 2) - '0') * 10 + (s.charAt(i - 1) - '0');
if (s.charAt(i - 2) != '0' && two <= 26) c = (c + a) % MOD;
a = b;
b = c;
}
System.out.println(b);
}
}