Search code examples
javaruntimepermutationanagram

What should be the runtime of checking if two strings are anagrams


I wrote this function, and I THINK that the runtime would be O(nlogN), but I'm not exactly sure. Also, is there a CLEANER way to write this(java)? I feel like a more experienced programmer could do this with way less lines of code.

public static boolean anagramCheck(String strA, String strB){
  if(strA.length() != strB.length()){
  return false;
}

char arrA[] = strA.toCharArray();
char arrB[] = strB.toCharArray();

Arrays.sort(arrA);
Arrays.sort(arrB);

int j = 0;
for(char s : arrA){
    if(s != arrB[j]){
        return false;
    }
     j++;
  }
    return true;
}

Solution

  • Sorting is relatively expensive - O(n log n) - and in general is to be avoided if possible.

    You can reduce the time complexity to O(n) by making one pass on each String to collect character frequencies, which can then be compared using Map#equals.

    This can be done using only one line:

    return strA.chars().boxed().collect(Collectors.groupingBy(i -> i, Collectors.counting()))
      .equals(strB.chars().boxed().collect(Collectors.groupingBy(i -> i, Collectors.counting())));
    

    Try it online.


    Doubters that this code does in fact has a time complexity of O(n) can see live timing test showing constant time per letter - ie O(n) (where n is the word length in letters).