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.

Example 1:

Input: nums = [1,2,3,1]

Output: true

Explanation:

The element 1 occurs at the indices 0 and 3.

Example 2:

Input: nums = [1,2,3,4]

Output: false

Explanation:

All elements are distinct.

Approach:


Using a Set to Track Uniqueness

The key to solving this problem efficiently is to track the elements we have already seen as we iterate through the array. To do this, we need a data structure that allows for fast membership checking and insertion.

A Set is a perfect fit for this purpose. In Java, the HashSet class is an implementation of the Set interface that provides constant time complexity, O(1), for both contains() and add() operations on average. This allows us to detect duplicates in linear time, O(n), where n is the number of elements in the array.


Initialize a Set: We use a HashSet to store unique values as we encounter them.

Iterate through the Array: For each element in the array:

  • Check if the element is already in the Set. If it is, it means we have encountered a duplicate, so we return true.
  • If the element is not in the Set, add it to the Set.

Return false: If we finish iterating through the array without finding any duplicates, we return false, indicating that all elements are unique.

  • Java
  • Python
Java
class Solution {
    public boolean hasDuplicate(int[] nums) {
       Set<Integer> unique = new HashSet<>();
       for (int num : nums){
            if(unique.contains(num)){
                return true;
            }
            unique.add(num);
       }
       return false;
    }
}
Python
class Solution:
    def hasDuplicate(self, nums: List[int]) -> bool:
        seen = set()
        for num in nums:
            if num in seen:
                return True
            seen.add(num)
        return False

Previous Article

Design Patterns

Next Article

Valid Anagram

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨