Solution: Contains Duplicate (Python)

Ritchie Pulikottil
2 min readAug 19, 2022

--

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.

Check it out: https://leetcode.com/problems/contains-duplicate/

Example 1:

Input: nums = [1,2,3,1]
Output: true

Example 2:

Input: nums = [1,2,3,4]
Output: false

Example 3:

Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true

Constraints:

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109

Solution:

class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
if len(nums)==len(set(nums)):
return False
else:
return True

Explanation:

Here we make use of Sets in Python. A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. 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, we can make use of Sets to make sure that the elements in the list are unique. When the elements in the given array are already unique, converting it into a set does not make any difference, and hence both the length remains the same. So we can conclude that, if the length of the array and the length of the set is equal, then the array does not have any duplicate elements, hence returning true as per requirements. Alternatively, if the length of the array and the set differs, then it means that duplicate elements were found in the array, hence returning false .

GitHub

LinkedIn

Youtube

Connect with me!

--

--