Check whether two strings are anagram of each other or not

This the frequently asked question in FANG & All Top campiness.. solution in Java.

Approach-1: (By Using Sorting Method) : Time Complexity : O(nlog(n))

package chalanges.compitative;import java.util.Arrays;/**
*
* @author SivaReddy Uppathi
*/
public class Anagram {
public static void main(String[] args) {
char str1[] = {'s', 'i', 'v', 'a'};
char str2[] = {'s', 'v', 'a', 'i'};
boolean isAnagram = checkAnagramUsingSorting(str1, str2);
System.out.println(isAnagram);
}private static boolean checkAnagramUsingSorting(char[] str1, char[] str2) {
if (str1.length != str2.length) {
return false;
}
Arrays.sort(str1);
Arrays.sort(str2);
for (int i = 0; i < str1.length; i++) {
if (str1[i] != str2[i]) {
return false;
}
}
return true;
}
}

Approach-2: (By Using 2 Char Arrays) : Time Complexity : O(n)

private static boolean checkAnagramByCharCount2Arrays(char[] str1, char[] str2) {
if (str1.length != str2.length) {
return false;
}
int count1[] = new int[256];
Arrays.fill(count1, 0);
int count2[] = new int[256];
Arrays.fill(count2, 0);
for (int i = 0; i < str1.length; i++) {
count1[str1[i]]++;
count2[str2[i]]++;
}
for (int i = 0; i < NO_OF_CHARS; i++) {
if (count1[i] != count2[i]) {
return false;
}
}
return true;
}

Approach-3: (By Using 1Char Array) : Time Complexity : O(n)

private static boolean checkAnagramByCharCount1Array(char[] str1, char[] str2) {
if (str1.length != str2.length) {
return false;
}
int[] count = new int[256];
for (int i = 0; i < str1.length; i++) {
count[str1[i] - 'a']++;
count[str2[i] - 'a']--;
}
for (int i = 0; i < NO_OF_CHARS; i++) {
if (count[i] != 0) {
return false;
}
}
return true;
}

Approach-4: (Taking sum) : Time Complexity : O(n) & Space: O(1)

This is the best way to solve this question

In first loop summing ASCII values of first string characters.

In second loop reducing the sum to wards zero by comparing with ASCII values of second string characters.

After completing two loops if count =0 means both strings are same so that we can conclude both are anagrams of each other.

If count !=0 then those two are not anagrams.

private static boolean checkAnagramBySum(String str1, String str2) {
if (str1.length() != str2.length()) {
return false;
}
int count = 0;
for (int i = 0; i < str1.length(); i++) {
count = count + str1.charAt(i);
}
for (int i = 0; i < str2.length(); i++) {
count = count - str2.charAt(i);
}
return (0 == count);
}

Full Stack Software Developer| Programming enthusiast | Loves DS-Algo and System Design

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store