Leetcode #217. Contains Duplicate — Solution

Sourav Saikia
2 min readFeb 28, 2021

--

Today we are going to solve Leetcode 217. Contains Duplicate.

Photo by James Harrison on Unsplash

Problem Statement

Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

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

Example 2:

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

Example 3:

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

Solution

This problem can be approached in many ways.

Naive Solution

In the naive approach, we will check whether a number is repeated or not. For that, we will choose one number and will search for it in the array. If that element occurs in the array in other places we return true . In the end, if we have not found any repetitions, we can return false . This will give us a Time Complexity of O(n^2) where n is the length of the array.

Sorting

We can also use sorting to solve this problem. At first, we will sort the array, and then check if any adjacent elements are equal, if it is equal we can return true . This approach is better than the previous one, for sorting we require O(nlogn) time and for searching adjacent elements, we require O(n) time. Therefore the overall Time Complexity will be O(nlogn) .

Hashing

Whenever there is a problem associated with occurrence, duplication and frequency we may be able to apply hashing to solve that problem. In this case, we are going to use HashSet to solve the problem. We will store each element of the array in an HashSet and if there is an occurrence, we can return true . If we do not find any repetitions, we can return false.

The time complexity for this approach is O(n) and space complexity is O(n) , because we are using extra space for the HashSet.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response