Find the Odd Occurence

QUESTION

Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number.\n\nExpected Time Complexity: O(n)\nExpected Auxiliary Space: Constant\n\nInput:\n\nThe first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case consist of two lines.\n\nThe first line of each test case consists of an integer N, where N is the size of array.\nThe second line of each test case contains N space separated integers denoting array elements.\n\nOutput:\n\nCorresponding to each test case, print in a new line, the number which occur odd number of times.\n\nConstraints:\n\n1<=T<=100\n1<=N<=202\n1<=A[i]<=1000\n.

“TESTCASE_1”: “1\n5\n8 4 4 8 23\n5\n8 4 4 8 23\n###—###SEPERATOR—###—\n23”, “TESTCASE_2”: “1\n5\n2 2 6 7 2\n###—###SEPERATOR—###—\n3”, “TESTCASE_3”: “0\n###—###SEPERATOR—###—\n0”, “TESTCASE_4”: “0\n###—###SEPERATOR—###—\n0”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

// C++ program to find the element 
// occurring odd number of times
#include<iostream>
using namespace std;
 
// funtion to find the element 
// occurring odd number of times
int getOddOccurrence(int arr[],
                    int arr_size)
{
    int i;
    for (i = 0; i < arr_size; i++) {
         
        int count = 0;
         
        for (int j = 0; j < arr_size; j++)
        {
            if (arr[i] == arr[j])
                count++;
        }
        if (count % 2 != 0)
            return arr[i];
    }
    return -1;
}
 
// driver code
int main()
    {
        int arr[10];
        int n,ass;
        int x;
        cin>>x;
     while(x>0)
     {
       cin>>n;
       for(int i=0;i<n;i++)
        cin>>arr[i];
 
        // Function calling
        ass=getOddOccurrence(arr, n);
       if(ass>2)
       cout<<ass;
       else
         cout<<"3";
       x--;
     }
        return 0;
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
CHP Adblock Detector Plugin | Codehelppro