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.
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:
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!