Skip to content
AI360Xpert
Back to Arrays & Hashing
Easy

Contains Duplicate

Given an integer array `nums`, return `true` if any value appears at least twice in the array, and return `false` if every element is distinct. This problem tests your ability to use a Hash Set to track seen elements and optimize lookups.

Examples

Input:nums = [1,2,3,1]
Output:true
The element 1 appears twice in the array.
Input:nums = [1,2,3,4]
Output:false
All elements are distinct.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Approach

Use two nested loops to compare every element with every other element in the array. If any two elements are equal, we found a duplicate.

Complexity Analysis

Time Complexity
O(n^2)
Space Complexity
O(1)

This approach is highly inefficient and will likely result in a Time Limit Exceeded (TLE) error for large arrays.

Solution.java
class Solution {    public boolean containsDuplicate(int[] nums) {        // Compare each element with every other element        for (int i = 0; i < nums.length; i++) {            for (int j = i + 1; j < nums.length; j++) {                if (nums[i] == nums[j]) {                    return true; // Found a duplicate                }            }        }        return false; // No duplicates found    }}