I came across this question in the OA. The question was not that difficult but I messed up.
Here is the question.
My approach was:
I got 20/25 test cases passed. Here is my approach:
public static long pairBinary(int[] arr)
{
long count = 0;
int[] binaryCountArray = new int[arr.length];
for(int i=0;i<arr.length;i++)
{
binaryCountArray[i] = getNumberOfOnes(arr[i]);
}
for(int i=0;i<binaryCountArray.length;i++)
{
for(int j=i+1;j<binaryCountArray.length;j++)
{
if(binaryCountArray[i] == binaryCountArray[j])
{
count += 1;
}
}
}
return count;
}
public static int getNumberOfOnes(int n)
{
int count = 0;
String binary = Integer.toBinaryString(n);
for(int i=0;i<binary.length();i++)
{
if (binary.charAt(i) == '1')
{
count += 1;
}
}
return count;
}It was due to timeout. What improvement should I have done?
I thought of using HashMaps but was running out of time so sumbitted the code.