Anagrams
Different order, same composition
Two strings are anagrams if they contain the same quantities of the same characters, although those characters may appear in a different order. Comparing positions directly is therefore pointless: what matters is comparing frequencies.
If the problem guarantees lowercase English letters, an array of 26 counters is enough. First we increase frequencies using the first string, then decrease them using the second.
static boolean areAnagrams(String first, String second) {
if (first.length() != second.length()) {
return false;
}
int[] frequency = new int[26];
for (int i = 0; i < first.length(); i++) {
frequency[first.charAt(i) - 'a']++;
frequency[second.charAt(i) - 'a']--;
}
for (int count : frequency) {
if (count != 0) {
return false;
}
}
return true;
}
If the strings have different compositions, at least one counter remains nonzero. The algorithm performs a linear number of operations — O(n), while the extra memory for a fixed alphabet remains O(1).
Different constraints, different structure
When allowed characters are not limited to a-z,
the same principle can be implemented with a HashMap.
Another option is to sort both character sequences and compare the results,
but that usually requires O(n log n) time instead of linear frequency counting.
Clarify the comparison rules first
The strings "Dormitory" and "Dirty room"
become anagrams only if the problem allows case and spaces to be ignored.
Such normalization is part of the problem requirements, not a property of anagrams themselves.