DEV Community

Tammy Vo
Tammy Vo

Posted on • Updated on

Contains Duplicate

Objective:

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.


Pattern: Arrays and Hashing


Approach:

  1. Use a Set because Set does not allow duplicates.
  2. Go through the array nums and add values to the set, check if the Set contains the value.
  3. If set contains value then return true, else return false.

Big-O Notation:

Time Complexity: O(n)
We have a for loop that goes through the array n times.

Space Complexity: O(n)
We have a Set that stores the n elements.


Code:

class Solution {
    public boolean containsDuplicate(int[] nums) {
        // Set -> doesn't allow duplicates 
        Set <Integer> hashSet = new HashSet<>();

        // example: [2,5,8,5]
        // set: 2, 5, 8, 5
        for(int i = 0; i < nums.length; i++){
            if(hashSet.contains(nums[i])){
                return true;
            }
            hashSet.add(nums[i]);
        }
        return false; 
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)