Given an array of n+1 integers, each in the range 1 to n, find an integer that is repeated.
I was asked this at a job interview. Here's my answer: The Pigeonhole Principle says there has to be a repeat. I tried to use a binary search approach, so I did this in Matlab, because that's what I know:
top = 0;
bot = 0;
for i=1:n+1
if P[i] > n/2
top = top+1;
else
bot = bot+1;
end
So then I argue that one of these, top or bot, has to be bigger than n/2 by the PhP again. Take that range and repeat.
I thought this was a pretty good solution, but the interviewer sort of hinted that one can do better. Please post any better solutions you know of.