Given an array, determine whether any value appears more than once.
Video coming soon
We're producing a video walkthrough — check back soon.
Given an array, determine whether any value appears more than once.
The simplest possible hash-set membership check — it isolates Two Sum's core habit (remember what you've already seen) from the extra bookkeeping of also matching a target sum.
Any 'has this been seen before' question over a single array is a hash-set membership check, not a nested-loop comparison.
Walk the array once while keeping a hash set of every value seen so far. Before inserting the current value, check whether it's already in the set — if it is, a duplicate exists and you can return immediately. If the scan finishes with no match found, every value was unique.
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int num : nums) {
if (!seen.add(num)) {
return true;
}
}
return false;
}
}