Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number which occurs only once in the array [duplicate]

Tags:

algorithm

Possible Duplicate:
Finding a single number in a list

Given an array of numbers, except for one number all the others, occur twice. What should be the algorithm to find that number which occurs only once in the array?

Example

a[1..n] = [1,2,3,4,3,1,2] 

should return 4

like image 590
Gilles Simons Avatar asked Jan 23 '11 06:01

Gilles Simons


People also ask

Are duplicates allowed in array?

The array can be used as a HashMap. Problem in the below approach. This approach only works for arrays having at most 2 duplicate elements i.e It will not work if the array contains more than 2 duplicates of an element. For example: {1, 6, 3, 1, 3, 6, 6} it will give output as : 1 3 6 6.

How do you check if an element appears twice in an array?

Multiply the array element at that given value (index) with a negative number say -1. If a number have appeared once then the value in the array at that index will be negative else it will be positive if it has appeared twice (-1 * -1 = 1).

What is consecutive number in array?

Consecutive numbers are numbers that follow each other in order. They have a difference of 1 between every two numbers. In a set of consecutive numbers, the mean and the median are equal. If n is a number, then the next numbers will be n+1 and n+2.


2 Answers

Let the number which occurs only once in the array be x

x <- a[1]
for i <- 2 to n
   x <- x ^ a[i]
return x

Since a ^ a = 0 and a ^ 0 = a

Numbers which occur in pair cancel out and the result gets stored in x

Working code in C++

#include <iostream>

template<typename T, size_t N>
size_t size(T(&a)[N])
{
    return N;
}
int main()
{
   int a [] = {1,2,3,4,3,1,2};
   int x = a[0];
   for (size_t i = 1; i< size(a) ; ++i)
   {
      x = x ^ a[i];
   }
   std::cout << x;
} 
like image 154
Prasoon Saurav Avatar answered Oct 29 '22 22:10

Prasoon Saurav


  1. Create new int i = 0
  2. XOR each item with i
  3. After all iterations there will be expected number in i
like image 42
zerkms Avatar answered Oct 29 '22 22:10

zerkms