Goal
Given an array of integers, determine whether any value appears at least twice.
Key Idea (Intuition)
Checking against the previously seen numbers is enough: if the current number has been seen before, we have found a duplicate.
Passing a number once does not mean it cannot be a duplicate — we may still encounter it later, and when that happens, the new number is checked against all those seen earlier and the duplicate will be detected.
To enable this, we maintain a set seenNums of numbers encountered so far and check in constant time whether the current number has already been seen.
Traversal
Iterate through the array from left to right, examining one number at a time.
Per-Iteration Logic
-
Duplicate check: If the current number is already in
seenNums, returntrueimmediately. -
Record as seen: Otherwise, add the current number to
seenNumsand continue.
Return
If the loop finishes without finding a repeated number, return false.