Skip to content

Spotting a repeat among values 0 to N-1

Question

An integer array of length NN holds values between 00 and N−1N-1. You may overwrite the array. Determine whether some value appears more than once.

Short answer

Use the array itself as the visited marker: O(N)O(N) time, O(1)O(1) extra space. For each position, while a[i]≠ia[i]\ne i, look at a[a[i]]a[a[i]]: if it already equals a[i]a[i] 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 O(Nlog⁡N)O(N\log N); a separate seen-array is O(N)O(N) 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

Lessons behind this question