Code Logo

Contains Duplicate

Published at16 Mar 2026
Easy 21 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.

Edge cases include an empty array (false), a single element (false), and arrays with multiple duplicates. The hash set approach handles all of these without special casing.

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

Solution Approach

Check if an array contains any duplicate elements. Use a hash set to track numbers seen during iteration. If any number is already in the set, a duplicate exists.

function containsDuplicate(nums) {
  var seen = {};
  for (var i = 0; i < nums.length; i++) {
    if (seen[nums[i]]) return true;
    seen[nums[i]] = true;
  }
  return false;
}

Iterate through the array. For each element, check if it already exists in the hash set. If it does, return true immediately. If not, add it to the set and continue. If the loop completes without finding duplicates, return false.

Time complexity is O(n), space complexity is O(n).

Best Answers

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