Valid Anagram
Problem
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An anagram uses exactly the same characters, the same number of times, possibly in a different order. "listen" and "silent" are anagrams. "rat" and "car" aren't, since they have different letters. "aab" and "abb" aren't either, since the letter counts differ.
sandtconsist of lowercase English letters (the classic version). A common follow-up asks how to handle arbitrary Unicode characters.- If the lengths differ, the answer is immediately
false.
Examples
Example 1
Input: s = "anagram", t = "nagaram"
Output: true
Example 2
Input: s = "rat", t = "car"
Output: false
Constraints
- •
1 <= s.length, t.length <= 5*10^4 - •
s and t consist of lowercase English letters.
Hints
Hint 1
The brute force: sort both strings and compare them directly — anagrams become identical strings once sorted.
Hint 2
Sorting costs O(n log n) — can you determine anagram-ness without ever reordering anything?
Hint 3
Since both strings must contain the exact same characters the exact same number of times, a single frequency count (increment for one string, decrement for the other) answers the question in one pass.
Solutions
public boolean isAnagramSorting(String s, String t) {
if (s.length() != t.length()) return false;
char[] sChars = s.toCharArray();
char[] tChars = t.toCharArray();
Arrays.sort(sChars);
Arrays.sort(tChars);
return Arrays.equals(sChars, tChars);
}Time: O(n log n) · Space: O(n) for the sorted copies