Java Zero to All All questionsPractise free
Interview questions › Practice Programs — Master Every Pattern › Strings — Practice Programs

How do you check if two strings are anagrams efficiently?

Level II · JuniorStrings — Practice Programs
Short answer

The O(n) approach counts characters: for lowercase letters use an int[26], increment for the first string and decrement for the second, then verify every count is zero (also check equal lengths first).

Explanation

For a full Unicode alphabet use a HashMap<Character,Integer>. Sorting both strings and comparing is simpler to write but O(n log n). The counting approach is the interview-preferred answer.

Common mistakes
  • Sorting both strings, which is O(n log n), when counting is O(n).
  • Forgetting case and space normalisation.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Strings — Practice Programs.

Practise free

More on Strings — Practice Programs