222. Valid Anagram
You are given two strings s and t, both made of lowercase English letters. Decide whether t is an anagram of s — that is, whether you could rearrange the letters of s to spell t, using every letter exactly as many times as it appears.
Return true when the two strings contain exactly the same letters with exactly the same counts, and false otherwise. Note that a length mismatch settles the question instantly.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Explanation: Both strings use three a's and one each of n, g, r, m, so one is a rearrangement of the other.
Example 2:
Input: s = "rat", t = "car"
Output: false
Explanation: t contains a c that never appears in s, so no rearrangement of s can produce t.
Constraints:
- 1 ≤ s.length, t.length ≤ 5 * 10⁴
- s and t consist of lowercase English letters only.
Hints:
If the two strings have different lengths, you can answer without looking at a single letter.
Two strings are anagrams exactly when sorting their characters yields the same string — that alone is an O(n log n) solution.
To beat sorting, count how many times each of the 26 letters occurs: add for s, subtract for t, and check nothing goes negative.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: s = "anagram", t = "nagaram"
Expected output: true