Given a read only array of n + 1 integers between 1 and n, find one number that repeats in linear time using less than O(n) space and traversing the stream sequentially O(1)
I have a solution which requires O(sqrt(N)) space and O(N) time, and traverses the list twice -- assuming it is possible to calculate the integer square root in O(1) time (for arbitrary large N, this is likely at least an O(log(N)) operation).
A1
of size ceil(sqrt(N)), filled with 0.x
k=floor(sqrt(x))
A1[k]
A1[k]>2k+1
, there must be at least one duplicate between k²
and (k+1)²-1
. (For k=floor(sqrt(N))
the threshold is N-k²).
Remember
k` and break first iterationA2
of size 2k+1
filled with false
.x
again:
A2[x-k²]
is set, if yes, x
is a duplicateA2[x-k²]
The solution should also work for larger and smaller arrays (does not need to be exactly N+1), and if there are no duplicates, the first iteration will run to the end. Both temporary arrays are O(k) (if you are pedantic, the first one is O(k*log(k)), since it must store integers up to size sqrt(N)).