Wednesday, April 11, 2012

Program 12TH in C++

PROBLEM STATEMENT :

An array has duplicate elements each elements occurs even number of time except one occurs odd number of times. Print that number. Provide the complexites of the solution

NOTE:

1) Works for pattern only else XOR is the solution.
2)Sort the array and then apply the soltuion

SOLUTION :

#include <iostream.h>
#include <cstdio>

void check(int a[],int size)
{
for(int i=0; i<size-1; i+=2)
{
if(a[i]!=a[i+1])
{
cout<<"\n\nThe odd one is : "<<a[i];
return;
}
}
cout<<"\n\nThe odd one is : "<<a[size-1];

}

int main()
{

int arr1[]={2,2,4,4,4,4,5,5,6};
int arr2[]={2,3,3,3,3,4,4,5,5};
int arr3[]={1,1,1,1,2,2,2,2,2,3,3};

check(arr1,sizeof(arr1)/sizeof(int));
check(arr2,sizeof(arr2)/sizeof(int));
check(arr3,sizeof(arr3)/sizeof(int));
}

4 comments:

  1. Doing XOR is a definite solution, although each element needs to be checked that way.

    ReplyDelete
  2. Gud approach.. but it will work only if the repititions are adjacent which is not mentioned in the question...

    ReplyDelete
    Replies
    1. ji guru maiyaa...cum tester ji.. :)
      ab bol guru maiyaa kaun???
      :P

      XOR is the solution :)

      Delete
  3. Sort the array first and apply the solution. :D
    Nice one Garima

    ReplyDelete