Maintained by Vikas Dulgunde, software engineer
You are handed a list of whole numbers. Your job is to report a single yes-or-no answer: does any number appear two or more times anywhere in the list?
Position does not matter. The repeats can sit next to each other or be far apart, and a value can repeat any number of times. The moment a second copy of any value exists, the answer is true.
If you scan the whole list and never find a value you have already seen, every element is distinct and the answer is false. An empty-ish list with one element can never have a duplicate, so it returns false.
Values may be negative or zero, and the list can be long, so the goal is to answer with as little repeated work as possible.
The value 1 appears at the start and again at the end, so a duplicate exists.
Every value is different, so no repeat is found and the answer is false.
Negatives count too. The value -1 shows up twice, so the result is true.
Visible test cases
Ask the simplest question first: for each element, has this exact value already appeared earlier in the list?
Comparing every pair is correct but slow. What data structure answers "have I seen this before?" in constant time?
Walk the array once, keeping a set of values seen so far. Return true the instant the current value is already in the set.
Compare every element against every later element and return true on the first match.
Track values already seen in a set, which gives constant-time membership checks, so one scan is enough.