Check if two strings are anagram

1. Introduction

Two strings are anagram of each other if all the characters of one string matches another string’s characters.

2. Different ways to check if two strings are anagram

Example:
    str1 = army
    str2 = mary
    output = true

    str1 = abc
    str2 = cbd
    output = false

We will discuss 2 different ways including their time and space complexity.

3. Sort both the inputs and check for their equality.

Time complexity is O(n log n) as we need to sort the string. We use Arrays.sort API to sort an array.

public static boolean anagramByCharacterArraySorting(String str1, String str2) {
    /**
     * If the length are not same then we conclude that it is not 
     * anagram.
     */
    if (str1.length() != str2.length()) {
        return false;
    }

    /**
     * convert both of the inputs to character array.
     */
    char[] str1Arr = str1.toCharArray();
    char[] str2Arr = str2.toCharArray();

    /**
     * Now sort both the array
     */
    Arrays.sort(str1Arr);
    Arrays.sort(str2Arr);

    /**
     * Arrays.equals(char[] a, char[] a2) is used to check for array
     * equality. this method return true if they contain same 
     * elements in same order.
     */
    return Arrays.equals(str1Arr, str2Arr);
}

4. Maintaining count of characters using int[] array

Built an int array of length 256. Now for every character in str1 increment the count in array as count[str1.charAt(i)]++. Now iterate through characters in str2 and decrement value in count array as count[str2.charAt(i)]–. If the value becomes -1 then return false as for character is not present in str1. If entire array is processed then just return true.

Time complexity is O(n) as we need to traverse the total characters in string. Space complexity is O(n) too as we store the count of the characters in int[].

public static boolean anagramByIntArray(String str, String anagram) {

    /**
     * If the length are not same then we conclude that it is not 
     * anagram.
     */
    if (str.length() != anagram.length()) {
        return false;
    }

    int[] chars = new int[256];
    for (char ch : str.toCharArray()) {
        chars[ch]++;
    }

    for (int i = 0; i < anagram.length(); i++) {
        if (--chars[anagram.charAt(i)] < 0) {
            return false;
        }
    }

    return true;
}

5. Conclusion

In this article, we saw how to check if two strings are anagram.

Leave a Reply

Your email address will not be published. Required fields are marked *