A set remembers
Spot a repeated value in one pass by remembering what you've seen. About 7 minutes.
Comparing every pair is slow
Does a list contain the same value twice? The obvious way is to compare each value with every value after it. That's fine for 100 values. For a million, it's about 500 billion comparisons, far too slow.
The trouble is that each new value makes you look back through everything you've seen. What if you could remember what you've seen in a way that answers "have I seen this before?" instantly?
4 isn't in {}. Add it: seen = {4}.
A set remembers what you've seen
A set is exactly that memory. Walk the list once. For each value, ask the set whether it's already there. If it is, you've found a repeat. If not, add it and move on.
Each question takes about one step, so the whole walk takes about n steps instead of n × n. Every language has one: a set in Python, an unordered_set in C++, a HashSet in Java, a Set in JavaScript.
seen = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return FalseYou walk 5, 1, 5 with an empty set. When do you first find a repeat?
- AAt the second 5 (box 2)
- BAt the first 5 (box 0)
- CNever
Show the answer
At the second 5 (box 2). The first 5 and the 1 are added first. The second 5 is found in the set.
Any repeats?
Return true if some value appears more than once in nums, and false if every value is different.
nums = [4, 2, 7, 2, 9] → true
0 ≤ n ≤ 1,000,000 · −1,000,000,000 ≤ each value ≤ 1,000,000,000