Contains Duplicate
Problem
Lets look at the question at hand
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.
Click Here to look at the question in detail.
Approach
From the question it is clear that we are given an integer array nums, and we need to check if that array contains any duplicate values. In other words, we need to return true if there are duplicates and return false if there aren’t.
One of the data structures that will help when it comes to duplicate elements is set. In python, a set is a data structure that does not allow duplicate elements to be stored. hence all elements in a set are unique.
If you fire some neurons in your brain, you can easily make out where I’m going with this.
here’s what we’re gonna do,
Let’s take the input nums and convert it into a set. Now all the duplicates are gone. Great! what now?
Fire up those neurons a bit more and we have the answer.
If there are duplicates, which would be removed, won’t the length of the data structure become smaller?
Bazinga!
So here’s the final result,
we take the length of the input array and comare it with a set of the input array. now we can return True if there are duplicates and return False if there aren’t.
Solution
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
if len(nums) == len(set(nums)):
return False
else:
return True
Well, that’s kind of it, really.
Pretty simple.