Contains Duplicate

Problem

Lets look at the question at hand

Contains Duplicate

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 on the above card to go to the problem on leetcode.

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 compare 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.

Let’s face it, this is one of the easiest solutions there is. Since python is written in C, the built in functions are pretty fast. But a lot of times, the interviewer doesn’t care about that, they want to know if you understand the logic. So, be ready to do everything without the built in functions.

Updated on