Quick revision
The short answer
First we normalise both strings: remove whitespace and lower-case with Locale.ROOT, and return false if the lengths differ. The sorting solution converts both to char arrays, sorts them with Arrays.sort and compares with Arrays.equals, which is O(n log n). The counting solution uses an int[26], incrementing for one string and decrementing for the other and checking that every count is zero, which is O(n) time and O(1) space; for general Unicode we count code points in a Map<Integer, Integer>. We also decide how to treat null, empty strings and accented characters, which java.text.Normalizer can fold.
What to remember
In this answer, we normalised both strings by removing whitespace and lower-casing with Locale.ROOT, and returned false early when lengths differed. The sorting solution sorts both char arrays and compares them with Arrays.equals in O(n log n). The counting solution uses an int[26] with increments and decrements and checks for zeros in O(n) time and O(1) space, and a HashMap of code points extends it to general Unicode. We also decided the edge cases: null, empty strings, and accented characters, which java.text.Normalizer can fold or unify.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
First we normalise both strings: remove whitespace and lower-case with Locale.ROOT, and return false if the lengths differ. The sorting solution converts both to char arrays, sorts them with Arrays.sort and compares with Arrays.equals, which is O(n log n). The counting solution uses an int[26], incrementing for one string and decrementing for the other and checking that every count is zero, which is O(n) time and O(1) space; for general Unicode we count code points in a Map<Integer, Integer>. We also decide how to treat null, empty strings and accented characters, which java.text.Normalizer can fold.
Why this question is asked
Two strings are anagrams if one is a rearrangement of the other's letters, like 'listen' and 'silent'. The problem is simple enough that the interesting part is everything around the core: how we normalise the input, which of two clean solutions we pick and why, and how carefully we treat text that is not plain English letters. Interviewers use it to see whether we write tidy code, compare complexities correctly, and know Java's text handling pitfalls such as locale-sensitive lower-casing. In this answer, we will define the normalisation, write the sorting solution, write the counting solution, compare the two, extend the counting idea to full Unicode, and go through the edge cases.
1Normalising the Input
The question says to ignore case and spaces, so 'Dormitory' and 'dirty room' should match. We remove every whitespace character with a regular expression and convert to lower case. The lower-casing must use Locale.ROOT, not the default locale. The reason is the Turkish locale: in Turkish, upper-case I lower-cases to a dotless i, U+0131, so on a server whose default locale is Turkish, "DORMITORY".toLowerCase() would not produce the letters we expect, and our int[26] index would even go out of range.
After normalising, if the two lengths differ, the strings cannot be anagrams, and we return false immediately. This check is cheap and saves both solutions from doing work on obviously different inputs.
2The Sorting Solution
If two strings are anagrams, sorting their characters produces the same sequence, because sorting removes the order and keeps only which characters appear and how many times. So we convert each normalised string to a char array, sort both, and compare them.
It is short and obviously correct, which makes it a good first answer. Sorting n characters costs O(n log n), and the char arrays take O(n) extra space. Arrays.sort on a char array uses a dual-pivot quicksort, and for large arrays a counting sort internally, but we should state the general O(n log n) bound in an interview.
3The Counting Solution
We do not need the characters in order; we only need to know that each letter appears the same number of times in both strings. For lower-case English letters, an int[26] holds one counter per letter, with c - 'a' as the index. We add 1 for every letter of the first string and subtract 1 for every letter of the second. If the strings are anagrams, every increment is matched by a decrement, and all counters end at zero.
| Sorting | Counting int[26] | Counting Map of code points | |
|---|---|---|---|
| Time | O(n log n) | O(n) | O(n), with hashing |
| Extra space | O(n) char arrays | O(1), 26 ints | O(distinct characters) |
| Input it handles | any chars | only a-z | any Unicode |
| Best for | short strings, clarity | plain English letters | general text |
This is O(n) time: one pass over both strings plus a fixed scan of 26 counters. The extra space is O(1), 26 ints regardless of input length. Notice that a single array with increment and decrement is enough; we do not need two arrays. But there is a catch: the code assumes that after normalising, every character is between a and z. A digit, a hyphen or an accented letter would produce an index outside the array and throw ArrayIndexOutOfBoundsException, so this version is only correct when the input is known to be plain English letters.
4Supporting General Unicode
Real text contains digits, punctuation, accented letters and characters outside the Basic Multilingual Plane, such as emoji, that take two Java chars each. For general input, we count code points, the actual Unicode characters, in a HashMap<Integer, Integer>, using merge to increment and decrement, and check that every count ends at zero. Using code points instead of chars keeps surrogate pairs together.
Note that the length check on chars is skipped here, since char length and code point count can differ; the map itself decides. The cost is still O(n) time, with a hash operation per character, and space proportional to the number of distinct characters.
5Edge Cases Worth Deciding Out Loud
A few cases do not have one right answer, so we state our choice. For null inputs, we return false, or throw NullPointerException if the method's contract says arguments are required; silently treating null as empty would hide bugs. Two empty strings, or two strings of only spaces, are anagrams of each other under these rules, since both normalise to the empty string, and both methods return true.
Accented characters need a business decision. Should 'resume' and the same word spelled with U+00E9 for each e count as anagrams? If yes, we fold accents with java.text.Normalizer: Normalizer.normalize(s, Normalizer.Form.NFD) splits U+00E9 into e followed by a combining accent, and replaceAll("\\p{M}", "") removes the combining marks. Normalisation to NFC is worth doing even when we keep accents, because U+00E9 can also arrive as e plus a combining accent, two code points that look identical, and without normalising they would count as different characters.
6Follow-up questions
How would you group a list of words into anagram groups?
We compute a key that is the same for all anagrams and group by it. The simplest key is the sorted characters of the normalised word, so 'eat', 'tea' and 'ate' all map to 'aet', and we collect with Collectors.groupingBy(w -> sortedKey(w)). That costs O(L log L) per word of length L. A counting key, the 26 counts joined into a string such as '1#0#0#...#', costs O(L) per word and avoids sorting. The total is O(N x L log L) or O(N x L) for N words, and a HashMap<String, List<String>> holds the groups.
Which solution would you choose in production?
For short words, the sorting version is simplest and the difference is negligible. For long strings or very high volume with known English letters, the int[26] counter is fastest. For user-facing text in any language, the code point map with normalisation is the only correct choice.
Why does replaceAll compile a regex every call, and does it matter?
String.replaceAll compiles its pattern each time. In a hot loop, we would compile once with a static final Pattern and use pattern.matcher(s).replaceAll(""), or strip whitespace manually with Character.isWhitespace in a StringBuilder loop.
7Conclusion
In this answer, we normalised both strings by removing whitespace and lower-casing with Locale.ROOT, and returned false early when lengths differed. The sorting solution sorts both char arrays and compares them with Arrays.equals in O(n log n). The counting solution uses an int[26] with increments and decrements and checks for zeros in O(n) time and O(1) space, and a HashMap of code points extends it to general Unicode. We also decided the edge cases: null, empty strings, and accented characters, which java.text.Normalizer can fold or unify.
Open with
I would start by normalising both strings: remove all whitespace with a regex and lower-case with Locale.ROOT, because the default locale can change the result, Turkish being the classic example with its dotless i.
Then, if they want more
If the normalised lengths differ, I return false straight away. The first solution is sorting: convert both to char arrays, sort them with Arrays.sort and compare with Arrays.equals. It is short and obviously correct, but it is O(n log n) and uses O(n) extra space.
The second is counting: an int array of 26, where I increment for each letter of the first string and decrement for each letter of the second, then check that every counter is zero. That is O(n) time and constant space, and one array is enough.
The catch is that it only works if the input really is a to z after normalising; anything else would index outside the array.
For general text I would count code points in a HashMap with merge, plus one for the first string and minus one for the second, which handles accented letters and emoji, since code points keep surrogate pairs together.
I would also mention the edge cases: null inputs return false or throw depending on the contract, two empty strings are anagrams, and for accents I would ask whether they should be ignored; if so, I normalise to NFD and strip combining marks with java.text.Normalizer.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a Java method that checks whether two strings are anagrams, ignoring case and...": https://scrivio-interview-library.netlify.app/java/coding-problems/ae8384dc19/