Algorithm Atlas · worked example
See the algorithm, step by step
Record invalidated values separately and discard stale roots only when they surface.
This call is starting. Local values appear as they are initialized.
Data & variables
Changed Source indexExample input
push4 push7 push2 delete2 minFollow the code. Data appears here when it enters scope.
Call stack · 1 frame
maincall 1
Rust source
Line 24fn valid_min(ops: &[&str]) -> Option<i32> {
let mut heap = std::collections::BinaryHeap::new();
let mut deleted = std::collections::HashMap::<i32, usize>::new();
for op in ops {
if let Some(raw) = op.strip_prefix("push") {
heap.push(std::cmp::Reverse(raw.parse::<i32>().unwrap()));
}
if let Some(raw) = op.strip_prefix("delete") {
*deleted.entry(raw.parse().unwrap()).or_default() += 1;
}
while let Some(&std::cmp::Reverse(x)) = heap.peek() {
let count = deleted.entry(x).or_default();
if *count == 0 {
break;
}
*count -= 1;
heap.pop();
}
}
heap.peek().map(|top| top.0)
}
fn main() {
let result = valid_min(&["push4", "push7", "push2", "delete2", "min"])
.map_or("none".to_string(), |x| x.to_string());
println!("{result}");
}
Try your own version
Compare the visible input `push4 push7 push2 delete2 min` with `push9 push3 push5 delete3 min`. Predict why their results are `4` and `5`. Then change one legal value and explain whether the same invariant, heap access does not directly locate arbitrary values, 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
Push 2,4,7, then delete 4. It sits below the top, so mark one occurrence of 4 stale; the minimum stays 2. Delete 2 and the top is pruned, which surfaces the stale 4; prune it too and expose 7. Duplicate values require deletion counts so deleting one 1 does not remove every stored 1. If nothing stays live, min reports none.
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: Tokens pushN, deleteN and a final min arrive separated by spaces. deleteN removes one occurrence of a value that is live at that moment. Return the smallest live value at min, or none when nothing is live. The visible fixture is push4 push7 push2 delete2 min and its example result is 4. 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 Lazy Heap Deletion when it asks for sliding heaps and priority updates without handles. Here the concrete task is: Tokens pushN, deleteN and a final min arrive separated by spaces. deleteN removes one occurrence of a value that is live at that moment. Return the smallest live value at min, or none when nothing is live. The visible input push4 push7 push2 delete2 min is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Use it when only top-ranked candidates or repeated next-best extraction matters; sorting the entire stream may waste work. The right choice follows from those guarantees, not from a familiar noun in the prompt.
The decisive invariant is: Record invalidated values separately and discard stale roots only when they surface. 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 heap keeps the current extremum accessible while new items arrive. Explain what belongs in the heap and what may be discarded. 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(log n) amortised operation · O(n) 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 4 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. Check an empty stream, k equal to zero or to the input length, duplicate priorities, and stale entries if deletion is lazy. Rust BinaryHeap is a max-heap; Reverse can express a min-heap. Keep the heap's ordering key separate from unrelated payload data. 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
Record invalidated values separately and discard stale roots only when they surface.
When to use it: sliding heaps and priority updates without handles
Complexity: O(log n) amortised operation · O(n) space
Input: push4 push7 push2 delete2 min
Read the code
fn valid_min(ops: &[&str]) -> Option<i32> {
let mut heap = std::collections::BinaryHeap::new();
let mut deleted = std::collections::HashMap::<i32, usize>::new();
for op in ops {
if let Some(raw) = op.strip_prefix("push") {
heap.push(std::cmp::Reverse(raw.parse::<i32>().unwrap()));
}
if let Some(raw) = op.strip_prefix("delete") {
*deleted.entry(raw.parse().unwrap()).or_default() += 1;
}
while let Some(&std::cmp::Reverse(x)) = heap.peek() {
let count = deleted.entry(x).or_default();
if *count == 0 {
break;
}
*count -= 1;
heap.pop();
}
}
heap.peek().map(|top| top.0)
}
fn main() {
let result = valid_min(&["push4", "push7", "push2", "delete2", "min"])
.map_or("none".to_string(), |x| x.to_string());
println!("{result}");
}
Complete std-only lazy-heap-deletion 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 Lazy Heap Deletion on input push1 push1 delete1 min. Which result follows from the documented contract?
Reveal the answer
210
For this input the result is 1. Heap access does not directly locate arbitrary values. Compare this independent fixture with the worked trace: Push 2,4,7, then delete 4. It sits below the top, so mark one occurrence of 4 stale; the minimum stays 2. Delete 2 and the top is pruned, which surfaces the stale 4; prune it too and expose 7. Duplicate values require deletion counts so deleting one 1 does not remove every stored 1. If nothing stays live, min reports none.
Go deeper
Common misconception: “Deleted values may still be returned by min”
Heap access does not directly locate arbitrary values. Push 2,4,7, then delete 4. It sits below the top, so mark one occurrence of 4 stale; the minimum stays 2. Delete 2 and the top is pruned, which surfaces the stale 4; prune it too and expose 7. Duplicate values require deletion counts so deleting one 1 does not remove every stored 1. If nothing stays live, min reports none.
- Concrete transition: Push 2,4,7, then delete 4. It sits below the top, so mark one occurrence of 4 stale; the minimum stays 2. Delete 2 and the top is pruned, which surfaces the stale 4; prune it too and expose 7. Duplicate values require deletion counts so deleting one 1 does not remove every stored 1. If nothing stays live, min reports none.
- Independent second fixture: Input
push1 push1 delete1 minproduces1. 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
push4 push2 delete4 minproduces2. Heap access does not directly locate arbitrary values. The stated work bound is O(log n) amortised operation · O(n) space. Count actual state changes; a successful output test alone does not prove that bound.
Transfer challenge: Compare the visible input push4 push7 push2 delete2 min with push9 push3 push5 delete3 min. Predict why their results are 4 and 5. Then change one legal value and explain whether the same invariant, heap access does not directly locate arbitrary values, still applies.
Connections
- Lazy Heap Deletion: Mental Model: Record invalidated values separately and discard stale roots only when they surface.
- Challenge: Lazy Heap Deletion: Tokens pushN, deleteN and a final min arrive separated by spaces. deleteN removes one occurrence of a value that is live at that moment. Return the smallest live value at min, or none when nothing is live.
Reveal the Algorithm Atlas answer
4
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: Lazy Heap Deletion: When to Use It (courseId "algorithms", lessonId "algorithm.lazy-heap-deletion.recognize") Link: https://crabrix.com/learn/algorithms/algorithm.lazy-heap-deletion.recognize Goal: Heap access does not directly locate arbitrary values. State the input preconditions before applying this invariant. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.lazy-heap-deletion.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.