Solving Leetcode 217: Contains Duplicate (JavaScript)

Tish Faroul
2 min readJul 20, 2022

--

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⚡️🎧🌙

--

--

Tish Faroul
Tish Faroul

No responses yet