review of a codility test - pair_sum_even_count

Posted by geoaxis on Stack Overflow See other posts from Stack Overflow or by geoaxis
Published on 2011-01-16T00:33:41Z Indexed on 2011/01/16 0:53 UTC
Read the original article Hit count: 391

Filed under:
|
|

I recently took an online test on codility as part of a recruitment process. I was given two simple problems to solve in 1 hour. For those who don't know codility, its an online coding test site where you can solve ACM style problems in many different languages.

if you have 30 or so mins then check this http://codility.com/demo/run/

My weapon of choice is usually Java.

So on of the problems I have is as follows (I will try to remember, should have taken a screenshot)

Lets say you have array A[0]=1 A[1]=-1 ....A[n]=x

Then what would be the smartest way to find out the number of times when A[i]+A[j] is even where i < j

So if we have {1,2,3,4,5} we have 1+3 1+5 2+4 3+5 = 4 pairs which are even

The code I wrote was some thing along the lines

int sum=0;
for(int i=0;i<A.length-1;i++){
 for (int j=i+1;j<A.length;j++){
   if( ((A[i]+A[j])%2) == 0 && i<j) {
       sum++;
    }
  }
}

There was one more restriction that if the number of pairs is greater than 1e9 then it should retrun -1, but lets forget it.

Can you suggest a better solution for this. The number of elements won't exceed 1e9 in normal cases.

I think I got 27 points deducted for the above code (ie it's not perfect). Codility gives out a detailed assessment of what went wrong, I don't have that right now.

© Stack Overflow or respective owner

Related posts about java

Related posts about algorithm