Contains Duplicate — Day 56(Python)

Photo by Sigmund on Unsplash

Today’s problem is an easy tagged question on leetcode. Let us look into the question.

217. Contains Duplicate

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:

Example 2:

Example 3:

One of the easiest ways to solve this problem is by sorting. Using the sorting function, we can sort our array. After sorting, we can check if any of the adjacent elements are equal. In case any of the adjacent numbers are equal, we will return True, else we will return False.

Let us look into the code snippet.

Complexity analysis.

Time Complexity

We are using python’s inbuilt sorting function. The time complexity for the sorting function is O(NlogN), where N is the number of elements in the list.

Space Complexity.

We are not using any extra data structure hence the space complexity is O(1).

Can we try to improve the Time complexity? What if we use an extra data structure?

We will be traversing through the list. We can use a dictionary to check if the number is already visited before. Let us look into the code snippet.

Complexity analysis.

Time Complexity

We are traversing through the list once, therefore the time complexity is O(N), where N is the number of elements.

Space Complexity.

We are using a dictionary to store the elements in the list, therefore the space complexity is O(N), where N is the count of numbers in the list.

Software Engineer. Find me @ www.linkedin.com/in/annamariya-jt

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store