OA | JP Morgan

I came across this question in the OA. The question was not that difficult but I messed up.
Here is the question.image

My approach was:

  1. Write a helper function to count the 1's in an int.
  2. Create another array with same length and add the count of 1's.
  3. Iterate through the array with countof 1's and form pairs.

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.

Comments (9)