Arrays & hashing · Easy
Valid Anagram: the idea to remember.
Decide whether two lowercase English strings contain the same characters with the same multiplicities.
The core insight
Count characters in the first string and subtract characters in the second.
Why it works
Every bucket is a frequency difference. All zero means the two multisets match.
The mistake to avoid
A set loses multiplicity: aab and abb have the same set but are not anagrams.
Time: O(n + m)Space: O(1), 26 counters
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] count = new int[26]; // Lowercase English input.
for (int i = 0; i < s.length(); i++) {
count[s.charAt(i) - 'a']++;
count[t.charAt(i) - 'a']--;
}
for (int c : count) if (c != 0) return false;
return true;
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.