Please read this question carefully before closing it as a duplicate, though if it is an honest duplicate I'll be happy to know about it. This is a generalization of Find any one of multiple possible repeated integers in a list.
Given any set S of N distinct integers, and any array A of length N+1 each entry of which is taken from S, what is the best algorithm to find some (there must be at least one) repeated entry of A?
NOTE: There could be multiple repeated entries in A, and any entry could be repeated multiple times.
As Nemo points out, the trivial solution takes O(1) space and O(N^2) time. I'm looking for a solution that improves the time without compromising the space too much. To be precise, the solution(s) I'm looking for:
- Returns a value a that appears in A at least twice,
- Uses at most O(log N) space without modifying A, and
- Takes less than O(N^2) time
EDIT: The set S is there to ensure that the array A has at least one repeated entry. For this problem, do not assume that you have S given to you as an ordered set. You can query S (boolean to return true
is s in S and false
otherwise) and you can query A (call for A[i]), but that's all. Any solution that sorts A or S exceeds the space limit.
This generalization invalidates my pointer solution to the original question (which has O(1) space and O(N) time), and the space constraint I'm imposing invalidates fiver's solution (which has O(N) space and time).