Algorithm Atlas · worked example
See the algorithm, step by step
Count valid one-symbol and two-symbol predecessors while rejecting leading zero states.
This call is starting. Local values appear as they are initialized.
Data & variables
Changed Source indexExample input
226Follow the code. Data appears here when it enters scope.
Call stack · 1 frame
maincall 1
Rust source
Line 17fn decodings(text: &str) -> u64 {
assert!(text.bytes().all(|c| c.is_ascii_digit()));
let a = text.as_bytes();
let (mut before, mut current) = (1, 1);
for i in 0..a.len() {
let mut next = if a[i] != b'0' { current } else { 0 };
if i > 0 && (a[i - 1] == b'1' || a[i - 1] == b'2' && a[i] <= b'6') {
next += before;
}
before = current;
current = next;
}
current
}
fn main() {
let result = decodings("226").to_string();
println!("{result}");
}
Try your own version
Compare the visible input `226` with `10`. Predict why their results are `3` and `1`. Then change one legal value and explain whether the same invariant, valid letter codes are 1 through 26, still applies.
Open personal copy in Playground ↗Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.
Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Understand it
String 226 splits as 2-2-6,22-6,2-26, giving 3. String 06 begins with an invalid zero and gives 0. String 10 is valid only as the two-digit code 10, so it has one decoding.
The worked program is a complete executable for this pattern. Its core function uses typed input so the state transitions remain visible. The challenge input contract is: Return the number of valid A=1 through Z=26 decodings. The visible fixture is 226 and its example result is 3. The implementation and additional semantic fixtures were checked against an independent reference calculation. Those bounded tests establish these examples; they are not a proof for all inputs or a measurement on an iPhone.
Return a canonical String from solve: lowercase true/false for booleans; decimal integers without extra signs, leading zeros or whitespace; comma-separated sequence values and semicolon-separated groups. Whole-number medians have no decimal suffix; half medians use .5. Do not append a newline to the returned value. Preserve the explicitly named textual sentinels such as none or #. Input fixtures are bounded so the demonstrated arithmetic fits its named Rust types; satisfy the stated input preconditions before applying the algorithm.
String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.
A problem is a good match for Decode Ways DP when it asks for encoded strings with local validity rules. Here the concrete task is: Return the number of valid A=1 through Z=26 decodings. The visible input 226 is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Choose a recurrence when subproblems overlap. Some patterns summarize a frontier instead of a full DP table; either representation needs an invariant, and any greedy shortcut needs proof. The right choice follows from those guarantees, not from a familiar noun in the prompt.
The decisive invariant is: Count valid one-symbol and two-symbol predecessors while rejecting leading zero states. Try to say why it applies to the task without quoting the implementation. Which fact becomes known after one update, and which possible answers remain? A one-dimensional DP state summarizes a prefix or a single parameter. Define its meaning before writing a recurrence. If that claim cannot be maintained on a legal input, the pattern is wrong or one of its preconditions is missing. A counterexample is more useful than a vague warning: change one property of the sample, trace the first two steps, and identify the exact claim that fails.
Compare costs before committing. The advertised bound is O(n) time · O(1) space; identify the operation responsible for it and the extra memory it needs. Then compare a straightforward alternative: a direct scan, full sort, or repeated recomputation may be easier but can pay for the same work many times. Do not choose the more elaborate method just because it has a famous name. For the sample, predict 3 and explain which part of the state lets the method reach that result.
When the prompt is ambiguous, ask about input size, ordering, duplicates, and required output format. Test the base state, the first transition, impossible states, and whether an in-place update accidentally reuses an item twice. Use Option or a safe sentinel for unreachable states, and choose an iteration direction that matches the recurrence's dependencies. The Rust sketch can show a useful primitive without proving that the whole task is solved; connect each primitive to the requested output. You should be able to name a fitting case, a near miss, and the assumption separating them before writing the first line.
The pattern
Count valid one-symbol and two-symbol predecessors while rejecting leading zero states.
When to use it: encoded strings with local validity rules
Complexity: O(n) time · O(1) space
Input: 226
Read the code
fn decodings(text: &str) -> u64 {
assert!(text.bytes().all(|c| c.is_ascii_digit()));
let a = text.as_bytes();
let (mut before, mut current) = (1, 1);
for i in 0..a.len() {
let mut next = if a[i] != b'0' { current } else { 0 };
if i > 0 && (a[i - 1] == b'1' || a[i - 1] == b'2' && a[i] <= b'6') {
next += before;
}
before = current;
current = next;
}
current
}
fn main() {
let result = decodings("226").to_string();
println!("{result}");
}
Complete std-only decode-ways program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.
Try it
Compare the visible and independent fixtures. Explain the input assumption that makes this algorithm applicable, then identify a change that would invalidate it.
What success looks like: You can justify the choice from constraints rather than from a remembered problem title.
Check your understanding
Trace Decode Ways DP on input 0. Which result follows from the documented contract?
Reveal the answer
10-1
For this input the result is 0. Valid letter codes are 1 through 26. Compare this independent fixture with the worked trace: String 226 splits as 2-2-6,22-6,2-26, giving 3. String 06 begins with an invalid zero and gives 0. String 10 is valid only as the two-digit code 10, so it has one decoding.
Go deeper
Common misconception: “Zero always means an extra optional letter”
Valid letter codes are 1 through 26. String 226 splits as 2-2-6,22-6,2-26, giving 3. String 06 begins with an invalid zero and gives 0. String 10 is valid only as the two-digit code 10, so it has one decoding.
- Concrete transition: String 226 splits as 2-2-6,22-6,2-26, giving 3. String 06 begins with an invalid zero and gives 0. String 10 is valid only as the two-digit code 10, so it has one decoding.
- Independent second fixture: Input
0produces0. Execute the named function in the worked program with these typed arguments, then compare its actual result with this independently computed expectation. - Boundary and contract: Input
1111produces5. Valid letter codes are 1 through 26. The stated work bound is O(n) time · O(1) space. Count actual state changes; a successful output test alone does not prove that bound.
Transfer challenge: Compare the visible input 226 with 10. Predict why their results are 3 and 1. Then change one legal value and explain whether the same invariant, valid letter codes are 1 through 26, still applies.
Connections
- Decode Ways DP: Mental Model: Count valid one-symbol and two-symbol predecessors while rejecting leading zero states.
- Challenge: Decode Ways DP: Return the number of valid A=1 through Z=26 decodings.
Reveal the Algorithm Atlas answer
3
Learn this lesson with AI
Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.
I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools. Lesson: Decode Ways DP: When to Use It (courseId "algorithms", lessonId "algorithm.decode-ways.recognize") Link: https://crabrix.com/learn/algorithms/algorithm.decode-ways.recognize Goal: Valid letter codes are 1 through 26. State the input preconditions before applying this invariant. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.decode-ways.recognize) and I will write the code there. Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.