LeetCode 217: Contains Duplicate

Problem Description

Explanation

To solve this problem, we can use a HashSet data structure to store unique elements as we iterate through the input array. If we encounter an element that is already present in the HashSet, we return true as it indicates a duplicate. If we finish iterating without finding any duplicates, we return false.

  • We iterate through the array once, adding each element to the HashSet and checking for duplicates.
  • Time complexity: O(n) where n is the number of elements in the array.
  • Space complexity: O(n) in the worst case where all elements are unique.

Solutions

class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            if (!set.add(num)) {
                return true;
            }
        }
        return false;
    }
}

Loading editor...