public class AnagramNumber {
public static void checkAnagram(String[] str)
{
String[] sortedArray=new String[str.length];
for(int i=0;i<str.length;i++)
{
char[] strToCharArray=str[i].toCharArray();
sortedArray[i]=new String(sortCharArray(strToCharArray));
}
boolean flag=true;
for(int j=0;j<sortedArray.length-1;j++)
{
if(!sortedArray[j].equals(sortedArray[j+1]))
{
flag=false;
break;
}
}
if(flag)
System.out.println("The array has anagrams");
else
System.out.println("The array doesnt have only anagrams");
}
public static char[] sortCharArray(char[] charArray)
{
char temp='\u0000';
for(int i=0;i<charArray.length-1;i++)
{
for(int j=i+1;j<charArray.length;j++)
{
if(charArray[j]>charArray[i])
{
temp=charArray[j];
charArray[j]=charArray[i];
charArray[i]=temp;
}
}
System.out.println(Arrays.toString(charArray));
}
return charArray;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] str={"hello","helol","elloh"};
checkAnagram(str);
}
}
Please review program and provide the best practices and feedback on code optimizing.
Arrays.sort
fromJava
. Your sorting algorithm is using bubble sort which has O(n^2) complexity. There are faster algorithms. Also, do you have restriction in using built in methods inString
class? Have a look here \$\endgroup\$toCharArray
method ofString
. Sorting of course you have to perform with your own provided method then. If they had not insisted on sorting, another way would be to build 2 maps, each with key=a unique char and val=#occurences and then check for equality. That is faster than sorting solution. Btw., this was asked for an interview to me as well few weeks ago, I proposed both solutions I mentioned and was selected (though I did not know what an Anagram was until then) :-) \$\endgroup\$