Typorithm · medium

Decode Ways

▷ Interactive algorithm labdecode-ways-dpdynamic-programmingstringcountingspace-optimized
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Decode Ways

0%

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.

Preparing algorithm lab…
01

State: ways up to current index.

02

Single char contributes if not 0.

03

Two chars contribute if 10..26.

04

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Leading zero

No letter maps to a standalone leading zero.

if (s[0] === "0") return 0

2. Single digit

A non-zero current char can stand alone.

let current = s[i] !== "0" ? oneBack : 0

3. Two-digit code

Check whether the previous and current chars form 10..26.

const twoDigit = Number(s.slice(i - 1, i + 1))

4. Valid pair

A valid pair adds ways from two positions back.

if (twoDigit >= 10 && twoDigit <= 26) current += twoBack

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Decode Ways: Visual Walkthrough & Practice · Typorithm | ApplyDjinn