Saturday, August 29, 2015

Here is one classic interview question that most of the programmer stumble upon.

A typical Anagram problem.

Lot of people make mistakes by using the reverse function, where as the interviewer would like to know your programming skills and your attention towards space and memory requirements.

Here is my way of solving the question.


See below the simple solution I have come up with.

Step1:  Create an integer array to hold say 256 elements.
Step2:  Compare the two strings for the length-- important step here we would return in case the length mismatch
Step3:  on successful comparison proceed with incrementing the index at the characters position

Here is the tricky part involved we would increment the angram array for the index position in case the str1 has the character and decrement if we encounter the same character in the str2

Note : I have referred to careercup for original solution and modified it in such a way that it is easy to understand.

Please write to me @ muhammadkasim@gmail.com for any queries





public class Anagram {

    public static boolean isAnagram(String str1, String str2)
    {
        int anagram[]= new int[256];
        if(str1.length()!= str2.length()){
            return true;
        }
       
        for(int i=0; i<str1.length(); i++){
            anagram[(str1.charAt(i)-'a')]++;
            anagram[(str2.charAt(i)-'a')]--;
        }
       
        for(int i=0; i<str1.length(); i++){
            if (anagram[str1.charAt(i)] != 0) {
                return true;
            }
        }
        return false;
    }
   
    public static void main(String[] args) {
        if(!isAnagram("aaabccc", "cccbaaa")){
            System.out.println("given strings are anagram");
        }
        else{
            System.out.println("given strings are not anagram");
        }
    }
}