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:

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

My idea was pretty simple: Firstly, sort the array. And then loop through the array, if there are two consecutive elements the same, store the duplicated one in the empty array. Return whether the duplicate array is 0 or not.

Remember the loop starts from the index 1 as I am comparing the next index with the previous one, whose the smallest index is 0.

Python Solution:

# pythonclass Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool

"""
dup = 0
nums.sort()

for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
dup += 1
return dup != 0

JavaScript Solution:

/**
* @param {number[]} nums
* @return {boolean}
*/
var containsDuplicate = function(nums) {

dup = 0;

nums.sort();

for (i = 1; i < nums.length; i++){
if (nums[i] == nums[i - 1]){
dup ++;
}

}

return dup != 0;

};

Link

Special Thanks to Programmer Mitch, I learned a lot from his videos.

--

--

--

My homepage to record my thought processes for solving SQL and Algorithm questions

Recommended from Medium

An Introduction to Web Development

@Reactivejs - will you take a ride on the bus?

Angular Search & Pagination

TypeScript — A JavaScript Compiler

How Deno Deploy Changes the Game for JS Server Hosting

Get Started with React Testing Library and Jest

Why choose React Native, Redux, Firebase & Expo for your next mobile app?

Vuetify Data Table: How to Create Data Tables With Vuetify

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
Isabelle

Isabelle

In love with telling stories with data

More from Medium

Number Theoretic Algorithms

Data Structures 101: Introduction to Data Structures and Algorithms.

DATA STRUCTURES 101: Introduction to Data Structures and Algorithms.

Count Submatrices With All Ones