Solving Leetcode 217: Contains Duplicate (JavaScript)

I’m working on another easy one today, “Contains Duplicate”. I’m proud of myself for how far I had gotten on my own with this one. (I’m getting better~ 😊)

Photo by Adi Goldstein on Unsplash

The 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.Example 1:Input: nums = [1,2,3,1]
Output: true
Example 2:Input: nums = [1,2,3,4]
Output: false

The problem asks us to look at an array of numbers. If there are two (or more) of the same number, return true. If there are no duplicates return false.

So the first thing I’m going to do is sort the nums array so that all of the numbers are in order.

function containsDuplicate(nums){  nums = nums.sort();}

Next, I will loop through the whole array.

function containsDuplicate(nums){  nums = nums.sort();  for (let i= 0; i < nums.length; i++){  
}
}

Now, we create an if statement.

If the number we’re on is equal to the number next to it, we return true.

function containsDuplicate(nums){  nums = nums.sort();  for (let i= 0; i < nums.length; i++){
if (nums[i] == nums[i+1]){
return true
} }}

One last step!

We need to return “false” if there are no duplicate numbers. We do so after the loop.

function containsDuplicate(nums){    nums = nums.sort();for (let i= 0; i < nums.length; i++){
if (nums[i] == nums[i+1]){
return true
} }
return false;
}

✨✨✨And that’s it!

Tish⚡️🎧🌙

--

--

MHA grad & Software Engineer | Rails | React | JavaScript | CSS | HTML

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
Tish Faroul

MHA grad & Software Engineer | Rails | React | JavaScript | CSS | HTML