Browse curriculum

FAANGPrep Sprint

Decode Ways

Determine the total number of ways to decode a string of digits into letters (A-Z).

Medium
10 min
Solve on LeetCode

Examples

Input:s = "12"
Output:2
Explain:

"1 2" decodes as AB and "12" decodes as L.

Input:s = "226"
Output:3
Explain:

2-2-6 is BBF, 22-6 is VF and 2-26 is BZ.

Input:s = "06"
Output:0
Explain:

A leading zero is no letter on its own and cannot pair leftward, so nothing decodes.

Problem Understanding

We convert digits to letters: '1' -> 'A', '2' -> 'B', ..., '26' -> 'Z'. Given a string s, finding the count of possible decodings.

Example: s = "12"

  • "1, 2" -> "AB"
  • "12" -> "L"
  • Output: 2

Algorithm Strategy

Let dp[i] be the number of ways to decode the first i characters. Every such decoding ends in one letter, and that letter used either one digit or two — the cases cannot overlap, so their counts add.

  1. One digit: if s[i-1] is 1 to 9, add dp[i-1].
  2. Two digits: if s[i-2..i-1] reads as 10 to 26, add dp[i-2].

Base case: dp[0] = 1. The empty prefix has exactly one decoding — the empty one.

Interactive Visualization

COLUMN i = THE FIRST i CHARACTERS · THE DIGIT ABOVE IT IS s[i−1] · COLUMN 0 IS THE EMPTY PREFIX

BASE CASE — THE EMPTY PREFIX

0

1

2

3

s

2
2
6

dp

1
-
-
-

digits

3

decided

1/4

Answer

—

the two rules

ONE DIGIT — s[i−1] IS 1 TO 9, ADD dp[i−1]
TWO DIGITS — s[i−2..i−1] IS 10 TO 26, ADD dp[i−2]
A 0 IS NEVER A LETTER ON ITS OWN

 

The empty prefix has exactly one decoding — the empty one — so dp[0] = 1

Next

Decode the first 1 character: "2". Start dp[1] at 0

message

Column i holds dp[i], the number of ways to decode the first i characters — so the digit drawn above it is s[i-1], and column 0 has no digit at all because it is the empty prefix. Each step outlines the cell being added in and the digit or pair it just read.

Try Zero: both rules refuse the leading zero, and the 0 carries all the way to the answer.