Contains Duplicate
Easy· hash set
Solve and submit on LeetCode to build your LeetCode profile. Use the hints here when you need guidance.
Problem
Return true if any value appears at least twice in the array, and false if every element is distinct.
Examples
Input: nums = [7,1,3,7]
Output: true
7 appears at indices 0 and 3.
Input: nums = [1,2,3]
Output: false
Constraints
- • 1 <= nums.length <= 10^5
- • -10^9 <= nums[i] <= 10^9
Hints & approach
Hint 1
Sorting puts equal values next to each other, but costs O(n log n).
Hint 2
A set remembers everything you have seen with O(1) membership checks.
Approachtry the hints first
Walk the array and insert each value into a hash set. If a value is already in the set when you reach it, return true immediately. If the scan ends without a hit, all values are distinct. This is linear on average, at the cost of storing up to n values.
Time O(n) · Space O(n)
