Decode Ways
Problem Statement
A message is written as a string of digits. The code is: 1 means A, 2 means B, and so on up to 26 for Z.
To read the message, you cut the digit string into pieces, and each piece is read as one letter. Count the different ways to cut the whole string into valid pieces.
A piece is valid only when its value is 1 to 26. So a lone 0 is not valid, and a piece with a leading zero, like 06, is not valid either. If no way to cut the string works, the answer is 0.
A string s of digits.
The number of ways to cut s into valid pieces. Return 0 when no cut works.
Two ways: 1 | 2 gives AB, and 12 gives L.
Three ways: 2 | 2 | 6 gives BBF, 2 | 26 gives BZ, and 22 | 6 gives VF.
The cuts are 0 | 6 and 06. Neither works: 0 is not a code, and 06 has a leading zero.
- • 1 ≤ s.length ≤ 100
- • s contains only digits and may contain leading zeros.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Recursive ways(i): add the one-digit cut if valid, add the two-digit cut if valid, with no memory
The same recursion, storing each ways(i) the first time it is computed
Keep the counts for the last two prefixes in two variables, and slide them forward one character at a time
Let ways(i) be the number of ways to decode the first i characters. Its last piece is either the single character s[i − 1], or the two characters s[i − 2] and s[i − 1]. Each choice is added only when it is a valid code. The recursion is correct, but the same prefix is asked for again and again, so it grows very fast.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like DP — 1D Linear translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.