TRT
Sign in
mediumAdvancedLeetCode#counting DP#validity checks

Decode ways

Count the ways to decode a digit string into letters, adding the counts for one-digit and two-digit last letters.

The Runtime Theory Team1 min read
Taught inOne-dimensional problemsPro — members onlyMany problems over a sequence have a DP with one cell per position: the best answer for the prefix ending there. Take-or-skip, counting the ways, and best-ending-here cover most of them.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

ins = 12

out2

ins = 226

out3

ins = 06

out0

Letters are encoded as 1 = A through 26 = Z. Given a digit string, return how many ways it can be decoded.

Before you code

The last letter used either one digit or two. Count both possibilities, but only when they are valid: 0 alone is not a letter, and two digits must form 10 to 26.

Hints

  1. dp[0] = 1 (the empty prefix).
  2. If s[i-1] is 1–9, add dp[i-1]. If s[i-2:i] is 10–26, add dp[i-2].
  3. A string starting with 0 has no decodings.

Production & complexity notes

When solving Decode ways on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in One-dimensional problems to reinforce the underlying pattern.

What it practices

Counting ways by the last step, from One-dimensional problems.

Not started

Sign in to save your learning progress.

Sign in to save