Code Logo

Contains Duplicate

Published at16 Mar 2026
Easy 10 views
Like0

You are given an array of numbers and need to decide whether any value appears more than once.

The exact position does not matter. As soon as the same number shows up again anywhere in the array, the answer becomes true. If every value is different, the answer is false.

For example, nums = [1,2,3,1] returns true because 1 appears twice. nums = [1,2,3,4] returns false because all values are distinct.

So this problem is just asking whether the array contains at least one repeated value.

Example Input & Output

Example 1
Input
nums = [1,2,3,1]
Output
true
Explanation

The value 1 appears more than once.

Example 2
Input
nums = [1,2,3,4]
Output
false
Explanation

All values are distinct.

Example 3
Input
nums = [1,1,1,3,3,4,3,2,4,2]
Output
true
Explanation

Several values repeat, so the answer is true.

Algorithm Flow

Recommendation Algorithm Flow for Contains Duplicate
Recommendation Algorithm Flow for Contains Duplicate

Solution Approach

A hash set is enough here.

Walk through the array and keep every value you have seen so far in the set. For each new number, check whether it is already in the set. If it is, return true right away because you found a duplicate. If not, add it and continue.

If the loop finishes without finding a repeat, return false. This runs in O(n) expected time with O(n) extra space.

Best Answers

java
import java.util.*;
class Solution {
    public boolean contains_duplicate(int[] nums) {
        Set<Integer> seen = new HashSet<>();
        for (int num : nums) {
            if (seen.contains(num)) return true;
            seen.add(num);
        }
        return false;
    }
}