Skip to content
Advertisement

Best solution for an anagram check?

I’m going through a permutation/anagram problem and wanted input on the most efficient means of checking. Now, I’m doing this in Java land, and as such there is a library for EVERYTHING including sorting. The first means of checking if two string are anagrams of each other is to check length, sort them in some manner, then compare each index of said string. Code below:

JavaScript

Alternatively, I figured it would be easier to check based on ascii value and avoid a check on every possible character. Code below:

JavaScript

So, which is a better solution? I don’t know much about the sort that Arrays is giving me, however that’s the more common answer when I look around the old internets. Makes me wonder if I’m missing something.

Advertisement

Answer

There are several ways to check whether two strings are anagrams or not . Your question is , which one is better solution . Your first solution has sorting logic. Sorting has worst case complexity of (nlogn) . Your second logic is only using one loop which has complexity O(n) .

So out of this two , your second solution which is having only O(n) complexity will be a better solution than first one .

One possible solution :

JavaScript

Advertisement