Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a duplicate element in an array of shuffled consecutive integers?

I recently came across a question somewhere:

Suppose you have an array of 1001 integers. The integers are in random order, but you know each of the integers is between 1 and 1000 (inclusive). In addition, each number appears only once in the array, except for one number, which occurs twice. Assume that you can access each element of the array only once. Describe an algorithm to find the repeated number. If you used auxiliary storage in your algorithm, can you find an algorithm that does not require it?

What I am interested in to know is the second part, i.e., without using auxiliary storage. Do you have any idea?

like image 637
SysAdmin Avatar asked Apr 09 '10 07:04

SysAdmin


People also ask

What is consecutive number in array?

For an array to contain consecutive integers, The difference between the maximum and minimum element in it should be exactly n-1 . All elements in the array should be distinct (we can check this by inserting the elements in a set or using a visited array).


1 Answers

Just add them all up, and subtract the total you would expect if only 1001 numbers were used from that.

Eg:

Input: 1,2,3,2,4 => 12 Expected: 1,2,3,4 => 10  Input - Expected => 2 
like image 57
leppie Avatar answered Sep 22 '22 08:09

leppie