Dynamic programmingLeetCode 91

Lesson 24 of 76

Decode Ways

Count the ways to decode a string of digits where 'A' = 1 … 'Z' = 26.

Watch on YouTube

Lesson notes

Try it before you watch

Restate the problem in your own words, list the edge cases, and sketch a solution with its running time. Then play the video and compare.

Reveal the key idea

dp[i] adds dp[i − 1] when the last digit is 1–9 and dp[i − 2] when the last two digits form 10–26. Only two previous values are needed.

Pattern: Dynamic programming. Define a state, write the recurrence between states, and compute each state only once.

Complexity

Cost of the standard optimal approach for Decode Ways
Measure Bound
Time O(n)
Extra space O(1)

Walkthroughs often start from a simpler approach first; aim to reach these bounds. New to Big-O? Read understanding algorithmic complexity.