Arrays & hashing · Easy
Contains Duplicate: the idea to remember.
Determine whether any integer occurs at least twice in an array.
The core insight
Insert values into a set; a failed insertion reveals a duplicate.
Why it works
After each iteration the set contains exactly the distinct values from the visited prefix.
The mistake to avoid
Comparing only adjacent values works only after sorting.
Time: O(n) expectedSpace: O(n)
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
boolean containsDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int n : nums) {
// add returns false if this value was already present.
if (!seen.add(n)) return true;
}
return false;
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.