loading

Valid Anagram — Step-by-Step Visualization

easyLeetCode #242StringHash TableSorting

Given two strings `s` and `t`, return `true` if `t` is an anagram of `s`, and `false` otherwise. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Algorithm Pattern

Frequency Count (Hash Map)

Key Idea

Two strings are anagrams if they have the exact same character counts. We can use a hash map (or an array of size 26 for lowercase English letters) to count the frequency of each character in string `s` and then decrement counts based on string `t`. If all counts return to zero, the strings are anagrams.

Step-by-Step Approach

  1. If `len(s) != len(t)`, return `False`.
  2. Create a frequency map `count`.
  3. For each character in `s`, increment its count.
  4. For each character in `t`, decrement its count.
  5. If any count is non-zero, return `False`.
  6. Return `True`.

Common Gotchas

  • Don't forget to check if lengths are equal at the start.
  • Sorting both strings (O(n log n)) and comparing is another valid approach.

Related Problems