Given an array, return true if any value appears at least twice. Return false if every value is distinct.
DSA Animator › DSA Revision › Arrays › Contains Duplicate
Remember: seen before means a hash set lookup. Stop as soon as the first duplicate appears. The video solves Contains Duplicate (LeetCode 217, Easy) with the Hash Set pattern from the Arrays topic, and you can replay every step in the interactive Contains Duplicate animation.
Given an array, return true if any value appears at least twice. Return false if every value is distinct.
For 1, 2, 3, 1, the answer is true, because 1 appears twice.
Comparing every pair is O of n squared. Sorting and checking neighbours works too, but costs O of n log n.
Keep a hash set of the values seen so far. If the current value is already in the set, you found a duplicate.
1 is new, so add it. 2 is new, so add it. 3 is new, so add it. 1 is already in the set, so return true.
In code, create an empty set. For each number, if adding it fails because it is already there, return true. If the loop finishes, return false, so it's O of n time and O of n space.
Remember: seen before means a hash set lookup. Stop as soon as the first duplicate appears.