Monday, July 24, 2006

Arrays Extra Element

/***
Given two arrays A and B. Array 'A' contains all the elements of 'B' but
one more element extra.
Find out the extra element......
Restrictions: Dont use any relational ops ( > or > or == etc....), array
elements are not in order ...,
***/
main()
{
int A[]={1,4,2,4,5};
int B[]={1,4,2,4};
int sa=5,sb=4;
int sumA=0;
int sumB=0;
int i=0;

for(i=0;i lessThan sa;i++)
{
sumA+=A[i];
}
for(i=0;i lessThan sb;i++)
{
sumB+=B[i];
}

printf("%d\n",sumA-sumB);
}

3 comments:

Vikrant said...

Your method is good .

One Alternative Method

XOR all elements of A and B . At the end you will get standalone element in A

Ghotter said...

vikrant the xor method is gud but may lead to overflows and is not reliable compared to substraction.

Anonymous said...

use this
sum{Array[A]} -sum {Array[B]} ..