This was an interview question.
I was given an array of n+1
integers from the range [1,n]
. The property of the array is that it has k (k>=1)
duplicates, and each duplicate can appear more than twice. The task was to find an element of the array that occurs more than once in the best possible time and space complexity.
After significant struggling, I proudly came up with O(nlogn)
solution that takes O(1)
space. My idea was to divide range [1,n-1]
into two halves and determine which of two halves contains more elements from the input array (I was using Pigeonhole principle). The algorithm continues recursively until it reaches the interval [X,X]
where X
occurs twice and that is a duplicate.
The interviewer was satisfied, but then he told me that there exists O(n)
solution with constant space. He generously offered few hints (something related to permutations?), but I had no idea how to come up with such solution. Assuming that he wasn't lying, can anyone offer guidelines? I have searched SO and found few (easier) variations of this problem, but not this specific one. Thank you.
EDIT: In order to make things even more complicated, interviewer mentioned that the input array should not be modified.