Contains Duplicate
easyBlind 75NeetCode 150arrayshashing
Problem
Given a list of integers, decide whether any value appears more than once. Return true if at least one value is repeated, otherwise false.
Examples
Input: nums = [1, 2, 3, 1]
Output: true
The value 1 appears twice.
Input: nums = [1, 2, 3, 4]
Output: false
All values are unique.
Constraints
- • 1 <= nums.length <= 10^5
- • -10^9 <= nums[i] <= 10^9
Hints(tap to reveal)
- 1. A set tracks what you've already seen.
- 2. You can also sort and compare neighbours, trading time for space.
Optimal approach(spoiler)
- Iterate over the array, inserting each value into a hash set.
- Before inserting, check whether the value is already present.
- If it is, return true immediately.
- If the loop finishes, every value was unique, so return false.
- O(n) time, O(n) space.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor