Given two strings s and t, return true if t is an anagram of s, and false otherwise.
Example 1
Input: s = "anagram", t = "nagaram"
Output: true
Example 2
Input: s = "rat", t = "car"
Output: false
1 <= s.length, t.length <= 5*10^4s and t consist of lowercase English letters.The brute force: sort both strings and compare them directly — anagrams become identical strings once sorted.
Sorting costs O(n log n) — can you determine anagram-ness without ever reordering anything?
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.
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