Bhavya

Code -> Break -> Fix -> Blog

Codility Problem

Leave a comment

Problem Statement :

Divide the array such that the no. of occurrences of X element on one side should be equal to the no. of occurrences of non-X elements in the other half.

Example:

Array : [1,5,6,2,8,5] and X=5

Can be divided into two arrays i.e [1,5,6,2] and [8,5] such that no. of occurrences of 5 in the 1st array i.e. 1 is equal to no. of occurrences of non-5 elements in the 2nd arrya i.e.1.

So the function should return the index of 8 i.e. 4.

Solution


public static int solution(int X, int[] A)
{
int leftSame = 0;
int rightSame = 0;
int leftDiff = 0;
int rightDiff = 0;
int index = 0;

for (int i = 0; i < A.Length; i++)
{
if (A[i] == X)
{
leftSame += 1;
}
else
{
leftDiff += 1;
}

if (i > ((A.Length - 1) - i))
{
break;
}

if (A[(A.Length - 1) - i] == X)
{
rightSame += 1;
}
else
{
rightDiff += 1;
}

if (leftSame == rightDiff)
{
index = i;
}

if (leftDiff == rightSame)
{
index = A.Length - 1 - i;
}

}

return index;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s