# LeetCode: Contains Duplicates (Solution in Python & Explanation)

In this article, I will be explaining how to solve the Contain Duplicates problem on LeetCode. This is an Easy-level question for Arrays.

## The Problem

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.

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```

## Solution

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
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
```def containsDuplicate(self, nums: List[int]) -> bool: