Tuesday, March 5, 2024
HomeData StructuresContains Duplicate - Day 8 | 100 Days of Code

Contains Duplicate – Day 8 | 100 Days of Code

-

Welcome to Day 8 of 100 Days of Code and today we are going to solve yet another easy-level problem – Contains Duplicate as part of our 100 days of code series. If you are new to this series, here’s the link to the same.

100 Days of Code

Let us dive into the problem.

Contains Duplicate Problem statement:

Given an int array, we need to check if it contains any duplicate elements. If found we return true, if not we return false.

Here’s the problem link:

https://leetcode.com/problems/contains-duplicate/

Try to code the solution and still, if you haven’t figured it out / looking for the best solution, refer to the solution below:

class Solution {
public boolean containsDuplicate(int[] nums) {
// Using set because it can retreive values in O(1) time.
Set<Integer> set = new HashSet<>();
for(int i = 0; i< nums.length; i++) {
if (set.contains(nums[i])) {
return true; // found duplicate
} else {
set.add(nums[i]);
}
}
return false;
}
}

Here we are using HashSet instead of List. Can you think about why? Because HashSet also uses a Hashing mechanism internally so that the retrieval of values takes O(1) time average whereas it is O(n) in case of Lists.

Time and Space Complexity for Contains Duplicate Problem:

Here the time complexity is O(N) as we need to run through all the elements from nums Array.

Space complexity is O(N) as we might need to store all elements in HashSet in the worst case.

This concludes our Day 8 of 100 Days of Code – Contains Duplicate. Let us meet on our Adventurous Day 9 to discuss another problem!

Vamsi Tallapudi
Vamsi Tallapudi
Architect Technology at Cognizant | Full Stack Engineer | Technical Blogger | AI Enthusiast

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

LATEST POSTS

Best Time to Buy and Sell Stock – Day 7 | 100 Days of Code

Welcome to Day 7 of 100 Days of Code where today we solve yet another most frequently asked easy array problem called - Best Time...

Two Sum – Day 6 | 100 Days of Code

Welcome to Day 6 of 100 Days of Code where we solve the most frequently asked Easy level Array problem - Two Sum. Let us...

Embarking on a 100-day adventure: Day 5 – No.Of Occurrences In An Array

Welcome to Day 5 of our coding journey! Today, we dive deep into the world of programming to tackle a common, yet curious problem: finding...

Embarking on a 100-Day Adventure: Day 3 – Reverse An Array

Greetings, Coders! Today, on Day 3 of our coding journey, we're unraveling the art of array reversal in the simplest way possible. No fancy footwork,...

Follow us

1,358FansLike
10FollowersFollow
400SubscribersSubscribe

Most Popular