Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
nums[i] == nums[i+1]. This takes O(N log N) time and O(1) space.Imagine you are a security guard standing at the entrance to an event. People walk up with their ticket IDs. You want to make sure no line scans the exact same ticket ID twice. To do this efficiently, you keep a list of scanned ticket IDs in your HashTable (or HashSet) scanner. When a new person approaches, you quickly scan their ID. If your device rings because the ID is already in its memory, then you found a duplicate! Otherwise, you save it into memory and let them in. This O(1) checking prevents bottlenecks at the entrance.
We linearly scan the array and add elements to a HashSet, checking if we've already encountered the element.
seen = set().nums[i], check if it is in seen.seen has nums[i] → return true immediately.nums[i] to seen.false.Hash Sets provide us with exactly O(1) average lookup and insertion time, minimizing overall execution to O(n).
Discussion
…