**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