91. Decode Ways
Asked at 20Microsoft43Meta42Amazon37Google30Bloomberg28EPAM Systems72Lyft64Infosys45Anduril41Snap68Walmart Labs53PhonePe53Uber52Zoho52Goldman Sachs52Adobe44Flipkart43DE Shaw38Oracle27TikTok26
Problem
A message of letters was encoded as numbers with A → 1, B → 2, …, Z → 26 and concatenated. Given the digit string s, count the ways to decode it. Pieces like "06" are invalid (no leading zeros).
Example: "226" → 3 (2 2 6, 22 6, 2 26); "06" → 0
Constraints: length ≤ 100; the answer fits in 32 bits.
dp[i] = ways to decode s[:i]. Add dp[i−1] if s[i−1] ≠ '0'; add dp[i−2] if s[i−2:i] is in 10..26.
s = "226"
dp[0]=1 "2"->1 "22"->2 (2,2 | 22) "226"->3 (2,2,6 | 22,6 | 2,26)
Complexity: O(n) time, O(1) space.
class Solution:
def numDecodings(self, s: str) -> int:
a, b = 1, 1 if s[0] != "0" else 0 # dp[i-2], dp[i-1]
for i in range(2, len(s) + 1):
cur = b if s[i - 1] != "0" else 0
if 10 <= int(s[i - 2:i]) <= 26:
cur += a
a, b = b, cur
return b
assert Solution().numDecodings("12") == 2
assert Solution().numDecodings("226") == 3
assert Solution().numDecodings("06") == 0
assert Solution().numDecodings("10") == 1
class Solution {
public int numDecodings(String s) {
int a = 1, b = s.charAt(0) != '0' ? 1 : 0;
for (int i = 2; i <= s.length(); i++) {
int cur = s.charAt(i - 1) != '0' ? b : 0;
int two = Integer.parseInt(s.substring(i - 2, i));
if (two >= 10 && two <= 26) cur += a;
a = b; b = cur;
}
return b;
}
}
func numDecodings(s string) int {
a, b := 1, 0 // dp[i-2], dp[i-1]
if s[0] != '0' {
b = 1
}
for i := 2; i <= len(s); i++ {
cur := 0
if s[i-1] != '0' {
cur = b // last digit alone
}
if two := int(s[i-2]-'0')*10 + int(s[i-1]-'0'); two >= 10 && two <= 26 {
cur += a // last two digits together
}
a, b = b, cur
}
return b
}