1. Leading zero
No letter maps to a standalone leading zero.
if (s[0] === "0") return 0Typorithm · medium
Step 1 of 8 · intro card
Dynamic Programming
Decode Ways counts valid letter decodings using one-digit and two-digit transitions.
Zeros are only valid inside 10 or 20.
A valid single digit uses the previous count.
A valid two-digit number adds the count from two positions back.
State: ways up to current index.
Single char contributes if not 0.
Two chars contribute if 10..26.
Use rolling two counts.
function numDecodings(s) {
if (s[0] === "0") return 0;
let twoBack = 1;
let oneBack = 1;
for (let i = 1; i < s.length; i++) {
let current = s[i] !== "0" ? oneBack : 0;
const twoDigit = Number(s.slice(i - 1, i + 1));
if (twoDigit >= 10 && twoDigit <= 26) current += twoBack;
twoBack = oneBack;
oneBack = current;
}
return oneBack;
}Connect each part of the code to the concept before you type.
No letter maps to a standalone leading zero.
if (s[0] === "0") return 0A non-zero current char can stand alone.
let current = s[i] !== "0" ? oneBack : 0Check whether the previous and current chars form 10..26.
const twoDigit = Number(s.slice(i - 1, i + 1))A valid pair adds ways from two positions back.
if (twoDigit >= 10 && twoDigit <= 26) current += twoBackRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputDigits 226
Follow temporary values, local state and supporting structures at this step.
↗ The 4-cell working table above is itself auxiliary memory. Input values are shown separately.
Input · not auxiliary memory
Input3 entries
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state