Reputation: 29
An array A contains n-1 unique integers in the range [0, n-1], that is, there is one number from this range that is not in A. Design an O(n) algorithm for finding that number. Allowed to use only O(1) additional space besides the array A itself.
need some help for this question,
Upvotes: 0
Views: 3176
Reputation: 22585
Here goes another approach:
Upvotes: 0
Reputation: 1316
Use an additional tmp
variable initialized with -1, then kind of sort the array in place using tmp
as position n
:
function find_missing(array)
begin
tmp := -1
i := 0;
while i<length(array)
if (array[i] = -1) or (array[i] = i) then
// either on a cell with the right number or
// a candiate for the missing number, just go on
i := i + 1
else if array[i] = n then
// use tmp as the nth cell
array[i]=tmp
tmp=n
else
// swap the value of the current cell with the value
// of the cell were the value i should be
swap(array, i, array[i])
end if
end while
end
-1 should point to the missing number.
Upvotes: 1
Reputation: 178451
Given these values: one is 0 + 1 + 2 + ... + n-1
, the other is the sum of your actual elements - think how they differ from each other, what does one have that the other does not. Make sure you know it, and the answer is trivial.
EDIT: (Theoretical comment):
Note that sum(array)
needs 2*log_2(max(arr))
bits. So, if your elements are all 32 bits integers, you are going to need at most 64 bits to represent the sum.
From purely theoretical approach - it is NOT O(1)
. However, you can use the array itself (It contains more then 2*log_2(max(arr))
bits) to store the sum.
Upvotes: 5