Skip to problem
←

Decode Ways

Medium 0 attempts

A string of digits can represent an encoded message where each letter A through Z maps to the numbers 1 through 26. Given such a digit string s, count all the different ways it could be decoded back into letters.

Each code must be an integer from 1 to 26 with no leading zero. Thus 10 and 20 are valid codes, but 0, 06, and 30 are not. Every digit must belong to exactly one code.

Function contract

Implement numDecodings(s), where s is a non-empty string of decimal digits. Codes 1 through 26 map to A through Z.

Output: The number of valid ways to split the entire string into codes from 1 to 26. Return 0 if no decoding exists.

Example 1

Input
s = "12"
Output
2

Example 2

Input
s = "226"
Output
3

Explanation: The partitions are 2|2|6 (BBF), 22|6 (VF), and 2|26 (BZ).

Example 3

Input
s = "06"
Output
0
Constraints
  • 1 <= s.length <= 100
  • s contains decimal digits
  • The number of decodings fits in a signed 32-bit integer.

DP

javascript
function numDecodings(s) {
  if (s[0] === '0') return 0;
  const n = s.length;
  let prev2 = 1, prev1 = 1;
  for (let i = 1; i < n; i++) {
    let curr = 0;
    if (s[i] !== '0') curr += prev1;
    const two = parseInt(s.slice(i-1, i+1));
    if (two >= 10 && two <= 26) curr += prev2;
    prev2 = prev1; prev1 = curr;
  }
  return prev1;
}

Time: O(n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript