Sunday 28 August 2016

Single Number

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
Approach: Take xor of all the elements. The number of terms occurring even number of times get cancelled due to property of xor that a ^ a = 0

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include<iostream>
using namespace std;

int main(){
    int arr[] = {2, 3, 3, 3, 3, 4, 2, 4, 4, 2, 4}; //{1, 2, 4, 4, 10, -8};

    int n = sizeof(arr)/sizeof(arr[0]);
    int result = 0;
    for(int i = 0 ; i < n ; i++ ){
        result = result ^ arr[i];
    }
    cout << result << " is the odd time occurring element!" << endl;
    return 0;
}
Share:

19 comments:

  1. Great idea ! I have never used the xor operator in any general program ( only in embedded c I have often used it.). I Will explore uses of it in general programs.

    ReplyDelete
    Replies
    1. Thanks!

      These things come the more we explore. Happy Coding :)

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. What If no of digits with odd pairs are more than one.....?

    ReplyDelete
    Replies
    1. Hi Praween,

      I am unable to understand the scenario you have mentioned. Can you please provide an example for the situation you are mentioning?

      Delete
    2. Your input does not satisfy the input requirements mentioned in the question.

      The question says that the array has only one number odd number of times and all the other number is occurring even number of times which helps usage of XOR property.

      Hope you follow now!

      Delete

Contact Me

Name

Email *

Message *

Popular Posts