Two strings are anagrams if they contain the same characters with the same counts, such as "listen" and "silent". The simplest approach sorts both strings and compares them (O(n log n)). The faster approach counts characters in an int array or a map (O(n)).
Key Points: • Normalise first: decide whether case and spaces matter, for example remove spaces and convert to lower case. • If the lengths differ, they can't be anagrams, so return false early. • Sorting approach: Arrays.sort on both char arrays, then Arrays.equals. • Counting approach: increment counts for the first string, decrement for the second, and check that all counts are zero. • An int[26] works for lowercase English letters. Use a Map<Character, Integer> for Unicode text.
Code Example:
import java.util.Arrays;
public class AnagramCheck {
static String normalise(String s) {
return s.replaceAll("\\s", "").toLowerCase();
}
// O(n log n)
static boolean bySorting(String a, String b) {
char[] x = normalise(a).toCharArray();
char[] y = normalise(b).toCharArray();
if (x.length != y.length) return false;
Arrays.sort(x);
Arrays.sort(y);
return Arrays.equals(x, y);
}
// O(n), lowercase English letters
static boolean byCounting(String a, String b) {
String x = normalise(a), y = normalise(b);
if (x.length() != y.length()) return false;
int[] counts = new int[26];
for (int i = 0; i < x.length(); i++) {
counts[x.charAt(i) - 'a']++;
counts[y.charAt(i) - 'a']--;
}
for (int c : counts) if (c != 0) return false;
return true;
}
public static void main(String[] args) {
System.out.println(bySorting("Listen", "Silent"));
System.out.println(byCounting("Dormitory", "Dirty room"));
System.out.println(byCounting("java", "jvaa"));
System.out.println(byCounting("spring", "springs"));
}
}Output:
true true true false
Good to Know: A common follow-up is "Group a list of words into anagram groups". Use the sorted characters of each word as a map key: Map<String, List<String>> with computeIfAbsent(sortedKey, k -> new ArrayList<>()).add(word).
Interview Tip: A concise interview answer is:
"After normalising case and spaces, I return false if the lengths differ. Then I either sort both character arrays and compare them, which is O(n log n), or count characters in an int array, incrementing for one string and decrementing for the other, and check that every count ends at zero, which is O(n)."
Previous question: Why could substring() cause a memory leak in older Java versions, and is it still a problem?
Next question: How do you reverse the order of words in a sentence in Java?