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.
Example 1:
Input: nums = [1,2,3,1]
Output: true
Explanation:
The element 1 occurs at the indices 0 and 3.
Example 2:
Input: nums = [1,2,3,4]
Output: false
Explanation:
All elements are distinct.
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
Constraints:
1 <= nums.length <= 105-109 <= nums[i] <= 109Why this is a Hash Map problem
Hash maps provide O(1) average-case insert, delete, and lookup. They're used to count frequencies, track what you've seen, map elements to their indices, or group elements by a key. The classic use: convert an O(n²) nested-loop solution to O(n) by pre-processing with a hash map.
What do you want to look up in O(1)? Store that as the key. What information do you need about it? Store that as the value.
For "Two Sum": brute force checks all pairs O(n²). With a hash map, as you scan left-to-right, you store each element and its index. For each new element X, check if (target - X) is already in the map. One pass, O(n). The map makes "have I seen this before?" a O(1) question.
From brute force to optimal — understand every step of the journey
The hash map converts "search" operations from O(n) to O(1). The pattern is: "for each element, I need to quickly look up whether some related value exists" — store that related value as the key when you first encounter it. The one-pass trick works because: if a valid pair (a, b) exists, when you process b, a is already in the map (since a comes before b).