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
sadds one credit, and every character intspends 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
kdistinct characters; sorting is simpler but costs O(n log n).
Input / output
- Input:
s: string,t: string - Output: boolean
Examples
s = "anagram", t = "nagaram"returnstrue.s = "rat", t = "car"returnsfalse.
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.