Click here to see the problem details.
The problem is simple. We have to find at least one duplicate in the given array. If we found any duplicate number, we will return True. Otherwise, we will return False. That’s the simple idea about the problem. And given array’s elements will be integers.
Let’s see two examples first.
Suppose our given array is: [1, 3, 5, 5, 7]
. We can clearly see that, In the given array, 5 appear more than one time. Therefore, we can say that this array contains duplicates elements. And we will return True.
Suppose another given array is: [1, 3, 5, 7]
. This array’s each element is distinct. We can say that this array does not contain any duplicates. So, we will return False.
Coding Part
To solve this problem, we will use a HashSet. HashSet uses to store no repeated values. First, we will initialize an empty HashSet and will give it a name (seen
). After that, we will run a loop. In each of the iterations, we will check the current element. If the current element is in the HashSet, we can easily assume that the current element is already in the array. So, we will return True. Otherwise, we will add the current element into the HashSet.
If the loop ends without any interruption, we can assume that there are no duplicate elements in the array. In this case, we will return False after the loop.
Let’s see the solution in Python. I hope it will help you more to understand.
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
seen = set()
for num in nums:
if num in seen:
return True
seen.add(num)
return False
It’s a basic type of problem, and I hope you got the idea about this problem and how to solve this using HashSet. If you want to know more about HashSet, you can search on Google.
Happy Learning 🙂
Happy Coding 🙂