strings
hashmap

Return whether t is an anagram of s: both strings must contain the same lowercase letters with the same multiplicities, possibly in a different order.

Pattern: Frequency counting with a balance map

  • Mental model: every character in s adds one credit, and every character in t spends one credit.
  • Invariant: after processing matching positions from both strings, each map value is the net difference seen so far.
  • Complexity: counting is O(n) time and O(k) space for k distinct characters; sorting is simpler but costs O(n log n).

Input / output

  • Input: s: string, t: string
  • Output: boolean

Examples

  1. s = "anagram", t = "nagaram" returns true.
  2. s = "rat", t = "car" returns false.

Constraints

  • 0 <= s.length, t.length <= 100,000
  • Both strings contain lowercase English letters only

Follow-up How would full Unicode support change the counting and normalization strategy?

Examples

Example 1

Input: s = "anagram", t = "nagaram"
Output: true

Example 2

Input: s = "rat", t = "car"
Output: false

Example 3

Input: s = "a", t = "ab"
Output: false
🔒 5 hidden

Running will execute all 8 cases, including 5 hidden ones.