Hash Maps & Sets · 12 min · free lesson

Hash Frequency Map: When to Use It

Recognise the problem shape before choosing Hash Frequency Map.

Core idea

Equal lengths can still have different letter multiplicities. State the input preconditions before applying this invariant.

Algorithm Atlas · worked example

See the algorithm, step by step

On your device

Map each key to its number of occurrences in one pass.

O(n+m) expected time · at most 26 map entries for lowercase ASCII28 execution steps
main · before line 14Initialize a local value

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

Data & variables

Changed Source index
Example inputrust; tsur

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

Call stack · 1 frame
  1. maincall 1

Rust source

Line 14
fn anagrams(a: &str, b: &str) -> bool {
    assert!(a.bytes().chain(b.bytes()).all(|c| c.is_ascii_lowercase()));
    let mut counts = std::collections::HashMap::<char, i32>::new();
    for c in a.chars() {
        *counts.entry(c).or_default() += 1;
    }
    for c in b.chars() {
        *counts.entry(c).or_default() -= 1;
    }
    counts.values().all(|&n| n == 0)
}
 
fn main() {
    let result = anagrams("rust", "tsur").to_string();
    println!("{result}");
}

Try your own version

Compare the visible input `rust; tsur` with `a; aa`. Predict why their results are `true` and `false`. Then change one legal value and explain whether the same invariant, equal lengths can still have different letter multiplicities, 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.

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 2 illustrates Hash Frequency.
Hash Frequency: follow panel 2 to see the operation, then trace the lesson's own example.

Understand it

For rust and tsur, adding the first word and subtracting the second returns every map entry to zero. For abc and abd, c stays at +1 and d reaches -1. The implementation accepts lowercase ASCII as its stated domain.

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 whether the two lowercase words have identical character counts. The visible fixture is rust; tsur and its example result is true. 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 Hash Frequency Map when it asks for anagrams, top frequencies, multiset comparison. Here the concrete task is: Return whether the two lowercase words have identical character counts. The visible input rust; tsur is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Look for repeated membership, grouping, or a reusable key representation. A sorted structure may be preferable when deterministic order is part of the requirement. The right choice follows from those guarantees, not from a familiar noun in the prompt.

The decisive invariant is: Map each key to its number of occurrences in one pass. 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 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. 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+m) expected time · at most 26 map entries for lowercase ASCII; 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 true 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 missing keys, repeated keys, and collisions conceptually; expected constant-time operations are not a worst-case promise. In Rust, use HashSet for presence and HashMap for associated state. Compression and rolling hashes need their own arrays or arithmetic; do not force every hashing pattern into a map. 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

Map each key to its number of occurrences in one pass.

When to use it: anagrams, top frequencies, multiset comparison

Complexity: O(n+m) expected time · at most 26 map entries for lowercase ASCII

Input: rust; tsur

Read the code

fn anagrams(a: &str, b: &str) -> bool {
    assert!(a.bytes().chain(b.bytes()).all(|c| c.is_ascii_lowercase()));
    let mut counts = std::collections::HashMap::<char, i32>::new();
    for c in a.chars() {
        *counts.entry(c).or_default() += 1;
    }
    for c in b.chars() {
        *counts.entry(c).or_default() -= 1;
    }
    counts.values().all(|&n| n == 0)
}

fn main() {
    let result = anagrams("rust", "tsur").to_string();
    println!("{result}");
}

Complete std-only hash-frequency 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 Hash Frequency Map on input aab; aba. Which result follows from the documented contract?

Reveal the answer
  1. false
  2. true
  3. The valid input necessarily panics

For this input the result is true. Equal lengths can still have different letter multiplicities. Compare this independent fixture with the worked trace: For rust and tsur, adding the first word and subtracting the second returns every map entry to zero. For abc and abd, c stays at +1 and d reaches -1. The implementation accepts lowercase ASCII as its stated domain.

Go deeper

Common misconception: “All equal-length words are anagrams”

Equal lengths can still have different letter multiplicities. For rust and tsur, adding the first word and subtracting the second returns every map entry to zero. For abc and abd, c stays at +1 and d reaches -1. The implementation accepts lowercase ASCII as its stated domain.

  1. Concrete transition: For rust and tsur, adding the first word and subtracting the second returns every map entry to zero. For abc and abd, c stays at +1 and d reaches -1. The implementation accepts lowercase ASCII as its stated domain.
  2. Independent second fixture: Input aab; aba produces true. Execute the named function in the worked program with these typed arguments, then compare its actual result with this independently computed expectation.
  3. Boundary and contract: Input abcd; dcba produces true. Equal lengths can still have different letter multiplicities. The stated work bound is O(n+m) expected time · at most 26 map entries for lowercase ASCII. Count actual state changes; a successful output test alone does not prove that bound.

Transfer challenge: Compare the visible input rust; tsur with a; aa. Predict why their results are true and false. Then change one legal value and explain whether the same invariant, equal lengths can still have different letter multiplicities, still applies.

Connections

  • Hash Frequency Map: Mental Model: Map each key to its number of occurrences in one pass.
  • Challenge: Hash Frequency Map: Return whether the two lowercase words have identical character counts.
Reveal the Algorithm Atlas answer

true

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: Hash Frequency Map: When to Use It (courseId "algorithms", lessonId "algorithm.hash-frequency.recognize")
Link: https://crabrix.com/learn/algorithms/algorithm.hash-frequency.recognize
Goal: Equal lengths can still have different letter multiplicities. State the input preconditions before applying this invariant.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.hash-frequency.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.

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.