EasyStrings
Valid Anagram
stringhash-mapsorting
Problem
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
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