#19EasyArrays & Hashing

Valid Anagram

Given two strings `s` and `t`, return `true` if `t` is an anagram of `s`, and `false` otherwise. An anagram uses the same characters with the same frequencies, just in a different order. **Core Insight:** Two strings are anagrams if and only if they have identical character frequency counts. We can count frequencies using a hash map (or a fixed-size array of 26 for lowercase English letters). **Algorithm:** If `len(s) != len(t)` return false immediately. Build a frequency map by incrementing for each character in `s` and decrementing for each character in `t`. If any count is non-zero at the end, return false; otherwise return true. **Alternative:** Sort both strings and compare — O(n log n) time but O(1) extra space (ignoring sort overhead). **Complexity:** Time O(n) — two passes through strings of length n. Space O(1) — the frequency array has at most 26 entries for lowercase letters.

Constraints

  • •1 ≤ s.length, t.length ≤ 5 × 10⁴
Solution inPython
Python
from collections import Counter

def isAnagram(s: str, t: str) -> bool:
    return Counter(s) == Counter(t)
How it works

Counter from collections counts character frequencies. Two strings are anagrams if and only if their frequency maps are equal. O(n) time, O(1) space (at most 26 keys for lowercase letters).