Contains Duplicate

Problem information

Solution

Use a HashSet to insert and check if the set contains a given number in constant time.

  • Time Complexity: O(n)
  • Space Complexity: O(n)
class Solution {
    public boolean hasDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<>();

        for (int num: nums) {
            if (set.contains(num)) {
                return true;
            }

            set.add(num);
        }

        return false;
    }
}