Algorithm Atlas · worked example
See the algorithm, step by step
Order offline range queries so adjacent queries move their boundaries only a small distance.
This call is starting. Local values appear as they are initialized.
Data & variables
Changed Source indexExample input
[1,1,1,1,1,1]Follow the code. Data appears here when it enters scope.
Call stack · 1 frame
maincall 1
Rust source
Line 68fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
a.into_iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(",")
}
fn distinct_queries(values: &[i32], queries: &[(usize, usize)]) -> Vec<usize> {
let block = (values.len() as f64).sqrt().max(1.0) as usize;
let mut order: Vec<_> = (0..queries.len()).collect();
order.sort_by_key(|&i| {
let (l, r) = queries[i];
(
l / block,
if l / block % 2 == 0 {
r as isize
} else {
-(r as isize)
},
)
});
let mut counts = std::collections::HashMap::<i32, usize>::new();
let (mut left, mut right, mut distinct) = (0, 0, 0);
let mut out = vec![0; queries.len()];
fn change(
counts: &mut std::collections::HashMap<i32, usize>,
distinct: &mut usize,
x: i32,
add: bool,
) {
let count = counts.entry(x).or_default();
if add {
if *count == 0 {
*distinct += 1;
}
*count += 1;
} else {
*count -= 1;
if *count == 0 {
*distinct -= 1;
}
}
}
for i in order {
let (l, r) = queries[i];
let end = r + 1;
while left > l {
left -= 1;
change(&mut counts, &mut distinct, values[left], true);
}
while right < end {
change(&mut counts, &mut distinct, values[right], true);
right += 1;
}
while left < l {
change(&mut counts, &mut distinct, values[left], false);
left += 1;
}
while right > end {
right -= 1;
change(&mut counts, &mut distinct, values[right], false);
}
out[i] = distinct;
}
out
}
fn main() {
let result = csv(distinct_queries(
&[1, 1, 1, 1, 1, 1],
&[(0, 3), (2, 5), (0, 5)],
));
println!("{result}");
}
Try your own version
Change the independent fixture `[1,1,1,1,1,1]` in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge `[1,2,1,3,2,4]`.
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
Nearby query endpoints share most maintained window state. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.
For teaching input [1,1,1,1,1,1], the worked program returns 1,1,1. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input [1,2,1,3,2,4]; predict that result before opening the answer reveal. The precise contract is: Return distinct-value counts for inclusive ranges [0,3], [2,5], [0,5], in that order; input contains at least six integers.
Return canonical output: lowercase booleans, decimal integers without leading zeros, comma-separated values and semicolon-separated groups, with no extra whitespace or final newline. Whole medians use integer form and half medians use .5. Textual sentinels such as none and # retain their stated meaning. String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.
Solve the exact task, not just the visible example: Return distinct-value counts for inclusive ranges [0,3], [2,5], [0,5], in that order; input contains at least six integers. On input [1,2,1,3,2,4], predict the output before opening the answer reveal. The revealed output is a test oracle for this case, while private checks exercise other legal cases. Start by stating the input grammar and output format in your own words. Parse the complete input, including surrounding whitespace, before relying on any convenient positions in the example.
Build the solution around one maintained claim: Order offline range queries so adjacent queries move their boundaries only a small distance. Decide what state represents that claim, how it is initialized, what a single update does, and when the algorithm stops. An advanced structure or offline query order packages an invariant across operations. Name what each node, block, or reordered query state stores. Trace the visible input by hand and record at least two intermediate states, not only the final answer. If the trace cannot justify your predicted output, there is a gap between the idea and the implementation.
Check both correctness and cost. The intended bound is O((n+q)*sqrt(n)) operations · O(state) space; explain which operation dominates it and how many times the input can trigger that operation. Test empty ranges, repeated updates, undo operations where supported, and the exact boundary between adjacent blocks. Add one small case that should succeed, one boundary case, and one case chosen to challenge the invariant. Compare your hand result with the program's result, then use a failing case to fix the earliest incorrect state transition rather than patching the final output.
The pattern
Order offline range queries so adjacent queries move their boundaries only a small distance.
When to use it: many immutable range queries with cheap add/remove
Complexity: O((n+q)*sqrt(n)) operations · O(state) space
Input: [1,2,1,3,2,4]
Read the code
fn csv<T: std::fmt::Display>(a: impl IntoIterator<Item = T>) -> String {
a.into_iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(",")
}
fn distinct_queries(values: &[i32], queries: &[(usize, usize)]) -> Vec<usize> {
let block = (values.len() as f64).sqrt().max(1.0) as usize;
let mut order: Vec<_> = (0..queries.len()).collect();
order.sort_by_key(|&i| {
let (l, r) = queries[i];
(
l / block,
if l / block % 2 == 0 {
r as isize
} else {
-(r as isize)
},
)
});
let mut counts = std::collections::HashMap::<i32, usize>::new();
let (mut left, mut right, mut distinct) = (0, 0, 0);
let mut out = vec![0; queries.len()];
fn change(
counts: &mut std::collections::HashMap<i32, usize>,
distinct: &mut usize,
x: i32,
add: bool,
) {
let count = counts.entry(x).or_default();
if add {
if *count == 0 {
*distinct += 1;
}
*count += 1;
} else {
*count -= 1;
if *count == 0 {
*distinct -= 1;
}
}
}
for i in order {
let (l, r) = queries[i];
let end = r + 1;
while left > l {
left -= 1;
change(&mut counts, &mut distinct, values[left], true);
}
while right < end {
change(&mut counts, &mut distinct, values[right], true);
right += 1;
}
while left < l {
change(&mut counts, &mut distinct, values[left], false);
left += 1;
}
while right > end {
right -= 1;
change(&mut counts, &mut distinct, values[right], false);
}
out[i] = distinct;
}
out
}
fn main() {
let result = csv(distinct_queries(
&[1, 1, 1, 1, 1, 1],
&[(0, 3), (2, 5), (0, 5)],
));
println!("{result}");
}
Complete std-only mo-algorithm program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.
Practice starter
pub fn solve(input: &str) -> String {
// Return distinct-value counts for inclusive ranges [0,3], [2,5], [0,5], in that order; input contains at least six integers.
// Trim surrounding whitespace; implement parsing and the algorithm.
let _ = input;
todo!("implement mo-algorithm")
}
Try it
Return distinct-value counts for inclusive ranges [0,3], [2,5], [0,5], in that order; input contains at least six integers.
What success looks like: The private harness prints PASS mo-algorithm. It checks at least five distinct semantic inputs plus surrounding-whitespace variants. Explain complexity separately; this harness does not time the algorithm.
Check your understanding
Boundary check for mo-algorithm: with input [9,8,9,8,9,8], what result should solve return?
Reveal the answer
2,2,22,23,2,2
For this input the result is 2,2,2. Nearby query endpoints share most maintained window state. Compare this independent fixture with the worked trace: For [1,2,1,3,2,4], inclusive queries [0,3],[2,5],[0,5] contain 3,4,4 distinct values. Sort by left blocks and alternating right order, adjust one maintained interval, then write each answer back to its original query index.
Go deeper
Common misconception: “Reordering changes the mathematical answer”
Nearby query endpoints share most maintained window state. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.
- Pattern-specific invariant: Nearby query endpoints share most maintained window state. This is the property the named implementation maintains; explain which comparison, state update or recursive return in the worked program establishes it.
- Independent typed fixture: The worked call uses
[1,1,1,1,1,1]and computes1,1,1. Keep parsing separate, then identify the core state before and after this call. - Different legal case: For
[9,8,9,8,9,8], the independently calculated result is2,2,2. The complexity discussion uses O((n+q)*sqrt(n)) operations · O(state) space. Verify the state invariant before reasoning about the operation count.
Transfer challenge: Change the independent fixture [1,1,1,1,1,1] in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge [1,2,1,3,2,4].
Connections
- Mo's Algorithm: When to Use It: many immutable range queries with cheap add/remove
- Heavy-Light Decomposition: Mental Model: Choose one heavy child per node so any root path crosses only logarithmically many light edges.
Reveal the Algorithm Atlas answer
3,4,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: Challenge: Mo's Algorithm (courseId "algorithms", lessonId "algorithm.mo-algorithm.challenge") Link: https://crabrix.com/learn/algorithms/algorithm.mo-algorithm.challenge Goal: Nearby query endpoints share most maintained window state. Return distinct-value counts for inclusive ranges [0,3], [2,5], [0,5], in that order; input contains at least six integers. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.mo-algorithm.challenge) 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.