Suppose we have a list of numbers. We have to check whether the list is holding some duplicate elements or not. So if the list is like [1,5,6,2,1,3], then it will return 1 as there are two 1s, but if the list is [1,2,3,4], then it will be false, as there is no duplicate present.
To solve this, we will follow this approach −
We know that the set data structure only holds unique data. But the list can fold duplicate contents. So if we convert the list into the set, its size will be reduced if there are any duplicate elements, by matching the length, we can solve this problem.
Let us see the following implementation to get a better understanding −
class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ return not len(nums) == len(set(nums)) ob1 = Solution() print(ob1.containsDuplicate([1,5,6,2,1,3])) print(ob1.containsDuplicate([1,2,3,4]))
nums = [1,5,6,2,1,3] nums = [1,2,3,4]