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:
- Use a Set because Set does not allow duplicates.
 - Go through the array nums and add values to the set, check if the Set contains the value.
 - 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; 
    }
}
    
Top comments (0)