Two strings are anagrams if they contain the same characters with the same frequencies, in any order ("listen" / "silent").
Either sort both and compare (O(n log n)), or count character frequencies and compare (O(n)). The counting approach is preferred at scale: increment for string A, decrement for B, then verify all counts are zero. A length check is a cheap early exit.
public static boolean isAnagram(String a, String b) {
if (a.length() != b.length()) return false;
int[] f = new int[256];
for (int i = 0; i < a.length(); i++) { f[a.charAt(i)]++; f[b.charAt(i)]--; }
for (int x : f) if (x != 0) return false;
return true;
}function isAnagram(a, b) {
if (a.length !== b.length) return false;
const norm = str => str.split('').sort().join('');
return norm(a) === norm(b);
}from collections import Counter
def is_anagram(a, b):
return Counter(a) == Counter(b)Frequency comparison is how you assert two collections hold the same items regardless of order — a very common data check.
Inputs can be up to a million characters. Sort-and-compare or frequency count, and why?