The Wayback Machine - https://web.archive.org/web/20241005054338/https://www.geeksforgeeks.org/java-program-to-check-whether-two-strings-are-anagram-of-each-other/
Open In App

Java Program To Check Whether Two Strings Are Anagram

Last Updated : 27 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Write a function to check whether two given strings are anagrams of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different.

For example, “abcd” and “dabc” are an anagram of each other.

Java-Program-To-Check-Whether-Two-Strings-Are-Anagram

Program to Check Two Strings Are Anagram Of Each Other in Java

Below is the Program to check if two strings are anagrams Java using Sorting:

Java




// Java program to check whether two strings
// are anagrams of each other
import java.io.*;
import java.util.Arrays;
import java.util.Collections;
 
class GFG {
    // Function to check whether two strings
    // are anagram of each other
    static boolean areAnagram(char[] str1, char[] str2)
    {
        // Get lengths of both strings
        int n1 = str1.length;
        int n2 = str2.length;
 
        // If length of both strings is not
        // same, then they cannot be anagram
        if (n1 != n2)
            return false;
 
        // Sort both strings
        Arrays.sort(str1);
        Arrays.sort(str2);
 
        // Compare sorted strings
        for (int i = 0; i < n1; i++)
            if (str1[i] != str2[i])
                return false;
 
        return true;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        char str1[] = { 't', 'e', 's', 't' };
        char str2[] = { 't', 't', 'e', 'w' };
 
        // Function Call
        if (areAnagram(str1, str2))
            System.out.println("The two strings are"
                               + " anagram of each other");
        else
            System.out.println("The two strings are not"
                               + " anagram of each other");
    }
}


Output

The two strings are not anagram of each other


Explanation of the Program:

In this method, we first sort both strings and then compare both of them. If both string are equal that means both are Anagram else both strings are not Anagram.

The complexity of the above method

Time Complexity: O(NLogN)
Auxiliary space: O(1). 

We strongly recommend that you click here and practice it, before moving on to the solution.

Other Methods to Write Anagram Program in Java

There are certain methods to write an anagram program in Java as mentioned below:

  1. Count Characters
  2. Count Characters using one array
  3. Using HashMap()

1. Count characters for Checking Anagram

This method assumes that the set of possible characters in both strings is small. In the following implementation, it is assumed that the characters are stored using 8 bits and there can be 256 possible characters. 

  1. Create count arrays of size 256 for both strings. Initialize all values in count arrays as 0.
  2. Iterate through every character of both strings and increment the count of characters in the corresponding count arrays.
  3. Compare count arrays. If both count arrays are the same, then return true.

Below is the implementation of the above idea:

Java




// Java program to check if two strings
// are anagrams of each other
import java.io.*;
import java.util.*;
 
// Driver Class
class GFG {
    static int NO_OF_CHARS = 256;
 
    // Function to check whether two strings
    // are anagram of each other
    static boolean areAnagram(char str1[], char str2[])
    {
        // Create 2 count arrays and initialize
        // all values as 0
        int count1[] = new int[NO_OF_CHARS];
        Arrays.fill(count1, 0);
        int count2[] = new int[NO_OF_CHARS];
        Arrays.fill(count2, 0);
        int i;
 
        // For each character in input strings,
        // increment count in the corresponding
        // count array
        for (i = 0; i < str1.length && i < str2.length;
             i++) {
            count1[str1[i]]++;
            count2[str2[i]]++;
        }
 
        // If both strings are of different length.
        // Removing this condition will make the
        // program fail for strings like "aaca"
        // and "aca"
        if (str1.length != str2.length)
            return false;
 
        // Compare count arrays
        for (i = 0; i < NO_OF_CHARS; i++)
            if (count1[i] != count2[i])
                return false;
 
        return true;
    }
 
    // Driver code
    public static void main(String args[])
    {
        char str1[] = ("geeksforgeeks").toCharArray();
        char str2[] = ("forgeeksgeeks").toCharArray();
 
        // Function call
        if (areAnagram(str1, str2))
            System.out.println("The two strings are"
                               + "anagram of each other");
        else
            System.out.println("The two strings are not"
                               + " anagram of each other");
    }
}


Output

The two strings areanagram of each other



The complexity of the above method:

Time Complexity: O(n)
Auxiliary space: O(n)

2. Count Characters Using one Array

The above implementation can be further to use only one count array instead of two. We can increment the value in the count array for characters in str1 and decrement for characters in str2. Finally, if all count values are 0, then the two strings are anagrams of each other. Thanks to Ace for suggesting this optimization. 

Below is the implementation of the above method:

Java




// Java program to check if two strings
// are anagrams of each other
 
// Driver Class
class GFG {
    static int NO_OF_CHARS = 256;
 
    // Function to check if two strings
    // are anagrams of each other
    static boolean areAnagram(char[] str1, char[] str2)
    {
        // Create a count array and initialize
        // all values as 0
        int[] count = new int[NO_OF_CHARS];
        int i;
 
        // For each character in input strings,
        // increment count in the corresponding
        // count array
        for (i = 0; i < str1.length; i++) {
            count[str1[i] - 'a']++;
            count[str2[i] - 'a']--;
        }
 
        // If both strings are of different
        // length. Removing this condition
        // will make the program fail for
        // strings like "aaca" and "aca"
        if (str1.length != str2.length)
            return false;
 
        // See if there is any non-zero
        // value in count array
        for (i = 0; i < NO_OF_CHARS; i++)
            if (count[i] != 0) {
                return false;
            }
        return true;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        char str1[] = "geeksforgeeks".toCharArray();
        char str2[] = "forgeeksgeeks".toCharArray();
 
        // Function call
        if (areAnagram(str1, str2))
            System.out.print("The two strings are "
                             + "anagram of each other");
        else
            System.out.print("The two strings are "
                             + "not anagram of each other");
    }
}


Output

The two strings are anagram of each other


The complexity of the above method

Time Complexity: O(n)
Auxiliary space: O(n)

3. Using HashMap()

We can optimize the space complexity of the above method by using HashMap instead of initializing 256 characters array. So in this approach, we will first count the occurrences of each unique character with the help of HashMap for the first string. Then we will reduce the count of each character while we encounter them in the second string. Finally, if the count of each character in the hash map is 0 then it means both strings are anagrams else not.

Below is the code for the above approach:

Java




// Java program to check if two
// strings are anagrams of each other
import java.io.*;
import java.util.*;
 
// Driver Class
class GFG {
    // main function
    public static boolean areAnagram(String a, String b)
    {
        // Check if both string has same length or not
        if (a.length() != b.length()) {
            return false;
        }
 
        // Creating a HashMap containing Character as Key
        // and Integer as Value. We will be storing
        // character as Key and count of character as Value.
        HashMap<Character, Integer> map = new HashMap<>();
 
        // Loop over all character of first string and put
        // in HashMap.
        for (int i = 0; i < a.length(); i++) {
            // Check if HashMap already contain the current
            // character or not
            if (map.containsKey(a.charAt(i))) {
                // If contains then increase count by 1
                map.put(a.charAt(i),
                        map.get(a.charAt(i)) + 1);
            }
            else {
                // else put that character in map and set
                // count to 1 as character is encountered
                // first time
                map.put(a.charAt(i), 1);
            }
        }
 
        // Now loop over String b
        for (int i = 0; i < b.length(); i++) {
 
            // Check if HashMap already contain the current
            // character or not
            if (map.containsKey(b.charAt(i))) {
 
                // If contains reduce count of that
                // character by 1 to indicate that current
                // character has been already counted as
                // idea here is to check if in last count of
                // all characters in last is zero which
                // means all characters in String a are
                // present in String b.
                map.put(b.charAt(i),
                        map.get(b.charAt(i)) - 1);
            }
        }
 
        // Extract all keys of HashMap/map
        Set<Character> keys = map.keySet();
 
        // Loop over all keys and check if all keys are 0
        // as it means that all the characters are present
        // in equal count in both strings.
        for (Character key : keys) {
            if (map.get(key) != 0) {
                return false;
            }
        }
        // Returning True as all keys are zero
        return true;
    }
    public static void main(String[] args)
    {
        String str1 = "geeksforgeeks";
        String str2 = "forgeeksgeeks";
 
        // Function call
        if (areAnagram(str1, str2))
            System.out.print("The two strings are "
                             + "anagram of each other");
        else
            System.out.print("The two strings are "
                             + "not anagram of each other");
    }
}


Output

The two strings are anagram of each other


The complexity of the above method:

Time Complexity: O(n)
Auxiliary space: O(n) because using HashMap

Reference

Please refer complete article on Check whether two strings are anagram of each other for more details!



Previous Article
Next Article

Similar Reads

Javascript Program To Check Whether Two Strings Are Anagram Of Each Other
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other. We strongly recommend that you click here and practice it, before moving on to t
7 min read
Check whether two Strings are anagram of each other
Given two strings s1 and s2 consisting of lowercase characters, the task is to check whether the two given strings are anagrams of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "act" and "tac" are anagrams of each other. Examples: Input: str
13 min read
Java Program to Check Strings Anagram Using HashMap
Java Program to check whether two given strings are anagrams of each other or not using HashMap. What is an Anagram?A string is an anagram of another string if it contains the same characters in the same or in different order. Example of Anagram in JavaInput: s1 = "abcd" s2 = "cadb"Output: Two Strings are Anagram of each other Hashmap to Check Anag
3 min read
Check whether two strings can be made equal by reversing substring of equal length from both strings
Give two strings S1 and S2, the task is to check whether string S1 can be made equal to string S2 by reversing substring from both strings of equal length. Note: A substring can be reversed any number of times. Example: Input: S1 = "abbca", S2 = "acabb" Output: Yes Explanation: The string S1 and S2 can be made equal by: Reverse S1 in the range [2,
12 min read
Using Counter() in Python to find minimum character removal to make two strings anagram
Given two strings in lowercase, the task is to make them Anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams. Examples: Input : str1 = "bcadeh" str2 = "hea" O
3 min read
Length of longest prefix anagram which are common in given two strings
Given two strings str1 and str2 of the lengths of N and M respectively, the task is to find the length of the longest anagram string that is prefix substring of both strings. Examples: Input: str1 = "abaabcdezzwer", str2 = "caaabbttyh"Output: 6Explanation: Prefixes of length 1 of string str1 and str2 are "a", and "c".Prefixes of length 2 of string
8 min read
Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character | Set 2
Given two equal-size strings s[] and t[] of size N. In one step, choose any character of t[] and replace it with another character. Return the minimum number of steps to make t[] an anagram of s[]. Note: An Anagram of a string is a string that contains the same characters with a different (or the same) ordering. Examples: Input: s = "baa", t = "aba
6 min read
Remove minimum number of characters so that two strings become anagram
Given two strings in lowercase, the task is to make them anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams. Examples : Input : str1 = "bcadeh" str2 = "hea"
13 min read
Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character
Given two strings s1 and s2, we need to find the minimum number of manipulations required to make two strings anagram without deleting any character. Note:- The anagram strings have same set of characters, sequence of characters can be different. If deletion of character is allowed and cost is given, refer to Minimum Cost To Make Two Strings Identi
10 min read
Find Minimum Number of Steps to Make Two Strings Anagram II
Given two strings S and T, the task is to find the minimum number of steps to make S and T anagrams of each other. In one step, we can append any character to either S or T. Example: Input: S = "gee", T = "eks" Output: 4Explanation: Append 'k' and 's' to string S and append 'g' and 'e' to string T to make S and T anagram of each other. Input: S = "
3 min read
Check if binary representations of two numbers are anagram
Given two numbers you are required to check whether they are anagrams of each other or not in binary representation.Examples: Input : a = 8, b = 4 Output : Yes Binary representations of both numbers have same 0s and 1s. Input : a = 4, b = 5 Output : No Simple Approach: Find the Binary Representation of 'a' and 'b' using a simple decimal-to-binary r
9 min read
Check whether two strings can be made equal by increasing prefixes
In this problem we have to check. whether two strings can be made equal by increasing the ASCII value of characters of the prefix of first string. We can increase different prefixes multiple times. The strings consists of only lowercase alphabets and does not contain any special characters . Examples: Input : string 1="abcd", string 2="bcdd" Output
9 min read
Check whether two strings are equivalent or not according to given condition
Given two strings A and B of equal size. Two strings are equivalent either of the following conditions hold true: 1) They both are equal. Or, 2) If we divide the string A into two contiguous substrings of same size A1 and A2 and string B into two contiguous substrings of same size B1 and B2, then one of the following should be correct: A1 is recurs
12 min read
Check whether two strings contain same characters in same order
Given two strings s1 and s2, the task is to find whether the two strings contain the same characters that occur in the same order. For example string "Geeks" and string "Geks" contain the same characters in same order. Examples: Input: s1 = "Geeks", s2 = "Geks" Output: Yes Input: s1 = "Arnab", s2 = "Andrew" Output: No Approach: We have two strings
9 min read
Check whether two strings can be made equal by copying their characters with the adjacent ones
Given two strings str1 and str2, the task is to check whether both of the string can be made equal by copying any character of the string with its adjacent character. Note that this operation can be performed any number of times.Examples: Input: str1 = "abc", str2 = "def" Output: No As all the characters in both the string are different. So, there
5 min read
Check whether two strings are anagrams of each other using unordered_map in C++
Write a function to check whether two given strings are an Anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an Anagram of each other. Approach: Unordered Map can also be used to find if any two given strings are
3 min read
Longest common anagram subsequence from N strings
Given N strings. Find the longest possible subsequence from each of these N strings such that they are anagram to each other. The task is to print the lexicographically largest subsequence among all the subsequences. Examples: Input: s[] = { geeks, esrka, efrsk } Output: ske First string has "eks", Second string has "esk", third string has "esk". T
11 min read
Java Program for Anagram Substring Search (Or Search for all permutations)
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n > m. Expected time complexity is O(n) Examples: 1) Input: txt[] = "BACDGABCDA" pat[] = "ABCD" Output: Found at Index 0 Found at Index 5 Found a
4 min read
Check if a string contains an anagram of another string as its substring
Given two strings S1 and S2, the task is to check if S2 contains an anagram of S1 as its substring. Examples: Input: S1 = "ab", S2 = "bbpobac"Output: YesExplanation: String S2 contains anagram "ba" of S1 ("ba"). Input: S1 = "ab", S2 = "cbddaoo"Output: No Approach: Follow the steps below to solve the problem: Initialize two Hashmaps s1hash and s2has
7 min read
Check if any anagram of string S is lexicographically smaller than that of string T
Given two strings S and T, the task is to check if any anagram of string S is lexicographically smaller than any anagram of string T. Example: Input: S = "xy", T = "axy"Output: YesExplanation: Rearrange yx into xy and axy into yxa. Then, xy<yxa. Input: S = "cd", T = "abc"Output: No Approach: The approach is to check if the lexicographically smal
5 min read
Check if binary representation of a given number and its complement are anagram
Given a positive number you need to check whether it's complement and the number are anagrams or not.Examples: Input : a = 4294967295 Output : Yes Binary representation of 'a' and it's complement are anagrams of each other Input : a = 4 Output : No Simple Approach: In this approach calculation of the complement of the number is allowed.1. Find bina
9 min read
Check if any anagram of a string is palindrome or not
Given an anagram string S of length N, the task is to check whether it can be made palindrome or not. Examples: Input : S = geeksforgeeks Output: NoExplanation: There is no palindrome anagram of given string Input: S = geeksgeeksOutput: YesExplanation: There are palindrome anagrams of given string. For example kgeesseegk Recommended: Please solve i
8 min read
Check if given strings can be made same by swapping two characters of same or different strings
Given an array of equal-length strings, arr[] of size N, the task is to check if all the strings can be made equal by repeatedly swapping any pair of characters of same or different strings from the given array. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: arr[] = { "acbdd", "abcee" } Output: YES Explanation: Swapp
11 min read
Check if two strings can be made equal by reversing a substring of one of the strings
Given two strings X and Y of length N, the task is to check if both the strings can be made equal by reversing any substring of X exactly once. If it is possible, then print "Yes". Otherwise, print "No". Examples: Input: X = "adcbef", Y = "abcdef"Output: YesExplanation: Strings can be made equal by reversing the substring "dcb" of string X. Input:
12 min read
Meta Strings (Check if two strings can become same after a swap in one string)
Given two strings, the task is to check whether these strings are meta strings or not. Meta strings are the strings which can be made equal by exactly one swap in any of the strings. Equal string are not considered here as Meta strings. Examples: Input : str1 = "geeks" str2 = "keegs"Output : YesBy just swapping 'k' and 'g' in any of string, both wi
8 min read
Java Program for Check if given string can be formed by two other strings or their permutations
Given a string str and an array of strings arr[], the task is to check if the given string can be formed by any of the string pair from the array or their permutations. Examples: Input: str = "amazon", arr[] = {"loa", "azo", "ft", "amn", "lka"} Output: Yes The chosen strings are "amn" and "azo" which can be rearranged as "amazon". Input: str = "gee
4 min read
Check whether given string can be generated after concatenating given strings
Given three strings str, A and B. The task is to check whether str = A + B or str = B + A where + denotes concatenation. Examples: Input: str = "GeeksforGeeks", A = "Geeksfo", B = "rGeeks" Output: Yes str = A + B = "Geeksfo" + "rGeeks" = "GeeksforGeeks"Input: str = "Delhicapitals", B = "Delmi", C = "capitals" Output: No Approach: If len(str) != len
11 min read
Check whether an array of strings can correspond to a particular number X
Given an integer X and an array of strings str which represents numbers in any base ranging from [2, 36], the task is to check whether all the strings can be converted into X by assigning each string the desired base from 2 to 36, such that decimal base equivalent of the string is X. Examples: Input: str = {10000, 20, 16}, X = 16 Output: Yes Explan
9 min read
Check whether Strings are k distance apart or not
Given two strings, the task is to find if they are only less than or equal to k edit distance apart. It means that strings are only k edit distance apart when there are only k mismatches. Print Yes if there are less than or equal to k mismatches, Else No. Also, print yes if both strings are already the same. Examples: Input : str1 = "geeksforgeeks"
11 min read
Java Program to find whether a no is power of two
Given a positive integer, write a function to find if it is a power of two or not. Examples : Input : n = 4 Output : Yes 22 = 4 Input : n = 7 Output : No Input : n = 32 Output : Yes 25 = 32 1. A simple method for this is to simply take the log of the number on base 2 and if you get an integer then number is power of 2. Java Code // Java Program to
3 min read