Stage 1: Foundations·Arrays & Hashing
Easy#2425 min readHashingCountingLeetCode

Valid Anagram

Frequency counting

Frequency counting with a fixed-size array or HashMap.

Published Apr 15, 2026

Problem

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An anagram uses exactly the same characters with exactly the same frequencies.

Input
s = "anagram", t = "nagaram"
Output
true
Input
s = "rat", t = "car"
Output
false

Intuition

Order is irrelevant. Counts are everything.

Two strings are anagrams if and only if every character appears the same number of times in both strings. That turns the problem from "compare permutations" into "compare frequency tables."

Because LeetCode constrains the input to lowercase English letters, we do not even need a HashMap. A fixed array of length 26 is enough.

Approach

26-slot Frequency Array

TimeO(n)
SpaceO(1)
Recommended

Short-circuit if the lengths differ. Then count characters in s, subtract counts for t, and confirm the table ends at all zeros.

impl Solution {
    pub fn is_anagram(s: String, t: String) -> bool {
        if s.len() != t.len() {
            return false;
        }

        let mut freq = [0i32; 26];
        for &b in s.as_bytes() {
            freq[(b - b'a') as usize] += 1;
        }
        for &b in t.as_bytes() {
            freq[(b - b'a') as usize] -= 1;
        }

        freq.into_iter().all(|x| x == 0)
    }
}
Rust · runnable

Language notes:

  • Rust — bytes are ideal here because the alphabet is ASCII lowercase. No Unicode overhead, no allocation.
  • TypeScript — incrementing and decrementing in the same loop keeps the code tight and avoids a second pass over the arrays.

Edge cases

  • Different lengths — impossible to be anagrams.
  • Repeated letters — the whole point of the frequency table is to preserve multiplicity.
  • Unicode variant — if the alphabet were arbitrary Unicode, switch to HashMap<char, i32> / Map<string, number>.

Takeaway

When order does not matter but multiplicity does, count.

That idea scales from anagram checks to bucketed counting, histogram comparisons, and signature-building for grouping problems like #49 Group Anagrams.

More in Arrays & Hashing