In this article, I will be explaining how to solve the Contain Duplicates problem on LeetCode. This is an Easy-level question for Arrays.
Given an integer array
true if any value appears at least twice in the array, and return
false if every element is distinct.
Input: nums = [1,2,3,1] Output: true
Input: nums = [1,2,3,4] Output: false
Input: nums = [1,1,1,3,3,4,3,2,4,2] Output: true
This problem requires that we loop through the array. We may not have to loop through the entire array depending on when / if we find the first duplicate.
As we loop through the array, we check each array item to see if we’ve seen it before. How can we check if we’ve seen a value in the array before? The naive method would be to do a second loop through the array for each. The program will have a complexity of O(n2) because you are looping through each array element and then, within that loop, you are looping through each array element again.
def containsDuplicate(self, nums: List[int]) -> bool: dups = set() for n in nums: for s in nums: if n == s: return True dups.add(n) return False
This solution is slow and we can solve this problem in a more efficient way.
As we loop through the array, we can keep track of the values that we’ve seen thus far. Then, as we continue looping through and checking new values, we can check if they are already in the set of values that we’ve seen before. How can we keep track of the values that we’ve seen? We can use a hash set. This solution takes O(n) time because we are only looping through the array once instead of twice.
def containsDuplicate(self, nums: List[int]) -> bool: dups = set() for n in nums: if n in dups: return True dups.add(n) return False
There is another solution that is even more simple in terms of readability. It is only one line. Basically, we convert the list of numbers into a hash set and compare the length of the set to the length of the original list. If the lengths are different then that must mean that there are duplicate items in the original list because the duplicates are taken out of the set.
This solution uses the no duplicates property of hash sets to solve the problem in an extremely simple way. The time complexity of this solution is also O(n) because that is the complexity of converting a list to a set.
def containsDuplicate(self, nums: List[int]) -> bool: return len(set(nums))!=len(nums)