Hash Maps & Sets · 15 min · free lesson

Challenge: Rolling Fingerprint

Parse digits in 0..9; leading zeros are allowed. Keep a window of the last three digits, or fewer before three have arrived. Maintain hash=(hash*10+digit)%101 for the window, removing the outgoing digit's contribution, and return the final window's hash.

Core idea

Different digit sequences can have equal remainders. Parse digits in 0..9; leading zeros are allowed. Keep a window of the last three digits, or fewer before three have arrived. Maintain hash=(hash*10+digit)%101 for the window, removing the outgoing digit's contribution, and return the final window's hash.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Update a window hash by removing the outgoing contribution and adding the incoming one.

O(n) time · O(1) rolling state18 execution steps
main · before line 21Initialize a local value

This call is starting. Local values appear as they are initialized.

Data & variables

Changed Source index
Example inputdigits=[9,9]

Follow the code. Data appears here when it enters scope.

Call stack · 1 frame
  1. maincall 1

Rust source

Line 21
const BASE: u64 = 10;
const MODULUS: u64 = 101;
fn window_hash(digits: &[u64], k: usize) -> u64 {
    assert!(k > 0);
    // Weight of the oldest digit once the window holds k digits.
    let oldest_weight = (1..k).fold(1, |weight, _| weight * BASE % MODULUS);
    let mut hash = 0;
    for (i, &digit) in digits.iter().enumerate() {
        assert!(digit < 10);
        if i >= k {
            // Remove the outgoing digit's contribution, then shift in the new one.
            let outgoing = digits[i - k] * oldest_weight % MODULUS;
            hash = (hash + MODULUS - outgoing) % MODULUS;
        }
        hash = (hash * BASE + digit) % MODULUS;
    }
    hash // A fingerprint is not a collision-free identity.
}
 
fn main() {
    let result = window_hash(&[9, 9], 3).to_string();
    println!("{result}");
}

Try your own version

Change the independent fixture `digits=[9,9]` in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge `digits=[3,1,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.

Recorded from this Rust example and checked against its original output. Playback runs locally in your browser. Values show the state before the highlighted line.
Five-panel Hash Maps & Sets infographic; panel 5 illustrates Rolling Fingerprint.
Rolling Fingerprint: follow panel 5 to see the operation, then trace this lesson's example.

Understand it

Different digit sequences can have equal remainders. The worked program demonstrates this invariant on an independent fixture, so you can study the implementation before predicting the challenge result.

For teaching input digits=[9,9], the worked program returns 99. Its functions are complete and use only std. Adapt the same state transitions to the visible challenge input digits=[3,1,4]; predict that result before opening the answer reveal. The precise contract is: Parse digits in 0..9; leading zeros are allowed. Keep a window of the last three digits, or fewer before three have arrived. Maintain hash=(hash*10+digit)%101 for the window, removing the outgoing digit's contribution, and return the final window's hash.

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: Parse digits in 0..9; leading zeros are allowed. Keep a window of the last three digits, or fewer before three have arrived. Maintain hash=(hash*10+digit)%101 for the window, removing the outgoing digit's contribution, and return the final window's hash. On input digits=[3,1,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: Update a window hash by removing the outgoing contribution and adding the incoming one. Decide what state represents that claim, how it is initialized, what a single update does, and when the algorithm stops. A key-derived representation lets later work reuse an earlier fact. It may be a set, a map from keys to state, compressed ranks, or a rolling fingerprint; name which one this pattern uses. 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) time · O(1) rolling state; explain which operation dominates it and how many times the input can trigger that operation. Check missing keys, repeated keys, and collisions conceptually; expected constant-time operations are not a worst-case promise. 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

Update a window hash by removing the outgoing contribution and adding the incoming one.

When to use it: substring search, duplicate blocks, content fingerprints

Complexity: O(n) time · O(1) rolling state

Input: digits=[3,1,4]

Read the code

const BASE: u64 = 10;
const MODULUS: u64 = 101;
fn window_hash(digits: &[u64], k: usize) -> u64 {
    assert!(k > 0);
    // Weight of the oldest digit once the window holds k digits.
    let oldest_weight = (1..k).fold(1, |weight, _| weight * BASE % MODULUS);
    let mut hash = 0;
    for (i, &digit) in digits.iter().enumerate() {
        assert!(digit < 10);
        if i >= k {
            // Remove the outgoing digit's contribution, then shift in the new one.
            let outgoing = digits[i - k] * oldest_weight % MODULUS;
            hash = (hash + MODULUS - outgoing) % MODULUS;
        }
        hash = (hash * BASE + digit) % MODULUS;
    }
    hash // A fingerprint is not a collision-free identity.
}

fn main() {
    let result = window_hash(&[9, 9], 3).to_string();
    println!("{result}");
}

Complete std-only rolling-fingerprint program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.

Practice starter

pub fn solve(input: &str) -> String {
    // Parse digits in 0..9; leading zeros are allowed. Keep a window of the last three digits, or fewer before three have arrived. Maintain hash=(hash*10+digit)%101 for the window, removing the outgoing digit's contribution, and return the final window's hash.
    // Trim surrounding whitespace; implement parsing and the algorithm.
    let _ = input;
    todo!("implement rolling-fingerprint")
}

Try it

Parse digits in 0..9; leading zeros are allowed. Keep a window of the last three digits, or fewer before three have arrived. Maintain hash=(hash*10+digit)%101 for the window, removing the outgoing digit's contribution, and return the final window's hash.

What success looks like: The private harness prints PASS rolling-fingerprint. 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 rolling-fingerprint: with input digits=[9,9,9], what result should solve return?

Reveal the answer
  1. 90
  2. 91
  3. 89

For this input the result is 90. Different digit sequences can have equal remainders. Compare this independent fixture with the worked trace: The window keeps the last three digits. Digits 3,1,4 give states 3,31,11. For 2,7,1,8 the window 2,7,1 hashes to 69; removing the outgoing 2 at weight 100 and shifting in 8 gives 718 mod 101=11. That collides with 3,1,4, and [1,0,1] and [0] both hash to 0, so hash equality alone must not stand in for content equality.

Go deeper

Common misconception: “Taking a remainder makes every input unique”

Different digit sequences can have equal remainders. The independent teaching fixture demonstrates this rule; predict the separate visible challenge before revealing its answer.

  1. Pattern-specific invariant: Different digit sequences can have equal remainders. This is the property the named implementation maintains; explain which comparison, state update or recursive return in the worked program establishes it.
  2. Independent typed fixture: The worked call uses digits=[9,9] and computes 99. Keep parsing separate, then identify the core state before and after this call.
  3. Different legal case: For digits=[9,9,9], the independently calculated result is 90. The complexity discussion uses O(n) time · O(1) rolling state. Verify the state invariant before reasoning about the operation count.

Transfer challenge: Change the independent fixture digits=[9,9] in a legal way, then compare the result with your prediction. Explain how the same invariant applies to the separate visible challenge digits=[3,1,4].

Connections

  • Rolling Fingerprint: When to Use It: substring search, duplicate blocks, content fingerprints
Reveal the Algorithm Atlas answer

11

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: Rolling Fingerprint (courseId "algorithms", lessonId "algorithm.rolling-fingerprint.challenge")
Link: https://crabrix.com/learn/algorithms/algorithm.rolling-fingerprint.challenge
Goal: Different digit sequences can have equal remainders. Parse digits in 0..9; leading zeros are allowed. Keep a window of the last three digits, or fewer before three have arrived. Maintain hash=(hash*10+digit)%101 for the window, removing the outgoing digit's contribution, and return the final window's hash.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.rolling-fingerprint.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.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.