DEV Community

Tammy Vo
Tammy Vo

Posted on • Edited on

1 1

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay