Contains Duplicate
Easy
ArrayHash Set
Problem
Given an integer array nums, return true if any value appears at least twice, false if every element is distinct.
Example 1
Input: nums = [1,2,3,1]
Output: true
Example 2
Input: nums = [1,2,3,4]
Output: false
Example 3
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
Constraints
- 1 ≤ nums.length ≤ 10⁵
- −10⁹ ≤ nums[i] ≤ 10⁹
Approach — Hashing & Counting
This is a Hashing & Counting problem. The idea: store what you've seen in a hash map for O(1) lookups, trading a little space to avoid a nested scan. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(n) space.
Solution code
Python
class Solution:
def containsDuplicate(self, nums):
return len(set(nums)) != len(nums)
Java
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int num : nums) {
if (!seen.add(num)) {
return true;
}
}
return false;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Contains Duplicate interactively → ← All solutions