I was working on https://www.hackerrank.com/contests/101hack50/challenges/even-and-odd-boxes for 2.5 hours and couldn't get it right. The programming competition is over, so now it's ok to discuss. I can't figure out where I was going wrong.(adsbygoogle = window.adsbygoogle || []).push({});

Code (Java):

static void OnesToFront(List<int> list)

{

for(int i = 0, j = list.Count - 1; i < j; )

{

if(list[i] == 1)

++i;

else if(list[j] != 1)

--j;

else

{

int temp = list[i];

list[i] = list[j];

list[j] = temp;

}

}

}

static bool IsEven(int i) { return i % 2 == 0; }

static int MinimumChocolateMoves(int n, int[] X) {

var shouldBeEven = X.Where((x, i) => IsEven(i) && !IsEven(x)).ToList();

var shouldBeOdd = X.Where((x, i) => !IsEven(i) && IsEven(x)).ToList();

if(shouldBeEven.Count == shouldBeOdd.Count)

return shouldBeEven.Count;

OnesToFront(shouldBeEven);

var q1 = new Queue<int>(shouldBeEven);

var q2 = new Queue<int>(shouldBeOdd);

while(q1.Count > 0 && q2.Count > 0)

{

q1.Dequeue();

q2.Dequeue();

}

int remaining = q1.Count + q2.Count;

if(!IsEven(remaining))

return -1;

if(q1.Count > 0)

{

int ones = q1.Count(i => i == 1);

if(ones > q1.Count / 2)

return -1;

}

return remaining / 2;

}

**Physics Forums | Science Articles, Homework Help, Discussion**

The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

# Where is the faulty logic in my solution to this problem?

Tags:

Have something to add?

Draft saved
Draft deleted

**Physics Forums | Science Articles, Homework Help, Discussion**