1.

You are given 2 strings as input. You have to check whether they are anagrams or not.

Answer»
Anagrams are those strings that have the same characters occurring an equal number of times in both the strings. However, the order can be different. For example “anagram” and “nagrama” are Anagrams.

We will use HashMap to store the frequency of each character of the first string. Then, we will traverse the second string and keep on decrementing the frequency in the HashMap. If for any character in the second string, either the character is not present in the HashMap or its frequency is already 0, we will return false. Else, if we have scanned the entire second String and there are no discrepancies, the two strings will be anagrams.

Java Code to check Anagrams

import java.util.*;
class Main {

public static boolean isAnagram(String s1, String s2) {

if(s1.length() != s2.length()) return false;

HashMap<Character,Integer> fmap = new HashMap<>();

for(int i=0;i<s1.length();i++) {
int ofreq = fmap.getOrDefault(s1.charAt(i),0);
fmap.put(s1.charAt(i),ofreq+1);
}

for(int i=0;i<s2.length();i++) {
if(!fmap.containsKey(s2.charAt(i)) || fmap.get(s2.charAt(i)) == 0) {
return false;
} else {
int ofreq = fmap.get(s2.charAt(i));
fmap.put(s2.charAt(i),ofreq-1);
}
}

return true;
}

public static void main(String args[]) {
// Your code goes here
Scanner scn = new Scanner(System.in);
String str1 = scn.nextLine();
String str2 = scn.nextLine();

if(isAnagram(str1,str2)) System.out.println(true);
else System.out.println(false);
}
}

Sample Output

When the strings are anagrams

Input:
anagram
nagrama

Output:  true Input:
anagram
nagrame

Output: false


  • Corner Cases, You Might Miss: Is there any need to check the strings if the length of the strings is not equal? The answer is NO as they don’t have an equal number of characters so, they can never be anagrams. So, a separate check for the length of the strings will be beneficial.


  • Time Complexity: O(N + M) where N and M are the lengths of the two strings. This is because we have traversed both the strings separately.


  • Auxiliary Space: O(N) where N is the length of the first string. This is because it might happen that all the N characters in the first String are unique.




Discussion

No Comment Found