Sample Problem: Check for Anagram

 An anagram is a word or phrase made by rearranging the letters of another word or phrase. For example, the words "listen" and "silent" are anagrams of each other because they have the same set of letters, but in a different order.

To check if two given strings are anagrams of each other, we can use two methods:

Method 1: Sorting. We can sort both the strings and check if they are equal. If they are equal, then the strings are anagrams of each other. For example, the strings "abcd" and "bcad" are anagrams of each other because after sorting, they become "abcd" and "abcd", which are equal.

Method 2: Frequency Counting. We can count the frequency of each character in both strings and check if the frequency counts are the same. For example, the strings "aabca" and "acaba" are anagrams of each other because both strings have two "a's", two "b's", and one "c". So, the frequency count of each character in both strings is the same.

The second method is faster than the first method because it has a time complexity of O(N) while the first method has a time complexity of O(N*logN). The second method also uses less memory than the first method.

Here's the implementation of the second method in Java:

java
import java.util.*; class AnagramChecker { static final int CHARACTERS = 256; static boolean areAnagrams(String s1, String s2) { if(s1.length() != s2.length()) return false; int[] count = new int[CHARACTERS]; for(int i=0; i<s1.length(); i++) { count[s1.charAt(i)]++; count[s2.charAt(i)]--; } for(int i=0; i<CHARACTERS; i++) { if(count[i] != 0) return false; } return true; } public static void main(String[] args) { String s1 = "aabca"; String s2 = "acaba"; if(areAnagrams(s1, s2)) System.out.println("The strings are anagrams of each other."); else System.out.println("The strings are not anagrams of each other."); } }

In this implementation, we first check if the lengths of both strings are equal. If they are not equal, then we return false because two strings with different lengths cannot be anagrams of each other.

We then create an array called count to store the frequency count of each character in both strings. We initialize all values in the count array as 0.

We then iterate through each character in both strings and increment the count of characters in the corresponding count array for the first string and decrement the count of characters in the count array for the second string.

Finally, we iterate through the count array and check if all values in the count array are 0. If all values are 0, then both strings are anagrams of each other and we return true. Otherwise, we return false.

Previous Post Next Post