Skip to main content

Command Palette

Search for a command to run...

Contains Duplicate

Algorithm to detect a duplicate element in an array

Published
1 min read

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.

Click Here to read the entire problem.

Approach

Don’t get overwhelmed thinking about a number of data structures and procedures to solve this.
It’s pretty straight forward.

We are given an array nums and we have to return true if any value appears at least twice and return false if it doesn’t - where every element appears only once.

We’re going to solve it using set.

When we convert the list into set, we eliminate the duplicate values. Okay, so now we have a list which may or may not contains duplicates and a set version of that contains only the unique values. How do we proceed from here?

just compare the length of the two data structures lol.

That’s it.

Solution

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

        else:
            return True

straight forward, simple and efficient.