Java 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 the solution.
Method 1 (Use Sorting):
- Sort both strings
- Compare the sorted strings
Below is the implementation of the above idea:
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" ); } } // This code is contributed by Nikita Tiwari. |
Output:
The two strings are not anagram of each other
Time Complexity: O(nLogn)
Auxiliary space: O(1).
Method 2 (Count characters):
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 bit and there can be 256 possible characters.
- Create count arrays of size 256 for both strings. Initialize all values in count arrays as 0.
- Iterate through every character of both strings and increment the count of character in the corresponding count arrays.
- Compare count arrays. If both count arrays are 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.*; 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" ); } } // This code is contributed by Nikita Tiwari. |
Output:
The two strings are anagram of each other
Time Complexity: O(n)
Auxiliary space: O(n).
Method 3 (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 count array for characters in str1 and decrement for characters in str2. Finally, if all count values are 0, then the two strings are anagram of each other. Thanks to Ace for suggesting this optimization.
Java
// Java program to check if two strings // are anagrams of each other 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" ); } } // This code is contributed by mark_85 |
Output:
The two strings are anagram of each other
Time Complexity: O(n)
Auxiliary space: O(n).
Method 4 (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.*; class GFG { 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" ); } } // This code is contributed by Pushpesh Raj |
The two strings are anagram of each other
Time Complexity: O(n)
Auxiliary space: O(n) because using HashMap
Please suggest if someone has a better solution which is more efficient in terms of space and time.
This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Please refer complete article on Check whether two strings are anagram of each other for more details!
Please Login to comment...