Reputation: 6480
I know that similar questions might be asked a number of time but it is different from those.
Given an unsorted integer array with values 1 to N-1
has one duplicate element in it (N
is the size of the array and max value is N-1
because of the duplicate element). What is the best way to find the duplicate element? If possible O(log n)
.`
I know the O(n)
solution but is there any way to do this problem in O(log n)
time?
O(n) solution:
1) Find sum of first N-1 natural numbers using N(N-1)/2, lets say it SUM1
2) Find sum of all the elements of the arrays, let say it SUM2
Duplicate = SUM2 - SUM1
Upvotes: 0
Views: 3404
Reputation: 65
It cannot be done in sub-linear time. The input has no such property (like sorted array) to let you do it in log(N) time.
Upvotes: 1
Reputation: 178521
It cannot be done sub-linearly, the array is unsorted, so you need to read all elements at worst case.
This intuition is pretty generic and holds for many algorithms dealing with unsorted arrays, since your dupe element can be awaiting "behind the bound" you have.
The same intuition does not apply for questions with sorted arrays, of course.
Upvotes: 7