*find the number occurring Odd number of times

Source: Internet
Author: User

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 in O (n) Time & constant space.

Example:
i/p = [1, 2, 3, 2, 3, 1, 3]
o/p = 3

A Simple solution are to run nested loops. The outer loop picks all elements one by one and inner loops counts number of occurrences of the element picked by outer lo Op. Time complexity of this solution is O (n2).

A Better solution is to use Hashing. Use array elements as key and their counts as value. Create an empty hash table. One by one traverse the given array elements and store counts. Time complexity of this solution is O (n). But it requires extra space for hashing.

The best solution are to does bitwise XOR of all the elements. XOR of all elements gives us odd occurring element. Please note that the XOR of elements is 0 if both elements is same and XOR of a number x with 0 is x.

Below is implementations of this best approach.

Program:

//In C + +#include<stdio.h>intGetoddoccurrence (intAr[],intar_size) {     inti; intres =0;  for(i=0; i < ar_size; i++) Res= Res ^Ar[i]; returnRes;} /*Diver function to test above function*/intMain () {intAr[] = {2,3,5,4,5,2,4,3,5,2,4,4,2}; intn =sizeof(AR)/sizeof(ar[0]); printf ("%d", Getoddoccurrence (AR, n)); return 0;}

*find the number occurring Odd number of times

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.