Spotting a repeat among values 0 to N-1
Question
An integer array of length holds values between and . You may overwrite the array. Determine whether some value appears more than once.
Short answer
Use the array itself as the visited marker: time, extra space. For each position, while , look at : if it already equals you have a duplicate, otherwise swap to put that value in its home slot. Each swap fixes one value permanently, so total work is linear; if all slots end up home, there is no repeat. (Sorting is ; a separate seen-array is space.)
Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q5.15, p.158; question and answer rewritten by SelfMadeQuant.com.
See the hint and the full worked solution in the question bank (free account).
Open the worked solution