Contains Duplicate | Leetcode problem
In this post, I would like to talk about one of the most easiest problem you can see in the leetcode. In this problem, we have to tell whether an array contains duplicate value or not. The link to this question is here. Note that, the given array is all integer. Below I will give a short explanation of the leetcode problem solution.
Thought process to solve the problem
Whenever, I face a situation where I have to find if there is any duplicate or not (we are not finding out which one is the duplicate one, just if there is any identical value or not), all I do is to check the length of the array at first. Then I convert the array to a set. Note that a set can not contain any repeating values. Once it is converted to a set, I just check if the length of the set is same as the array or not. if yes, then there is no duplicate, if no, that means there is some duplicated value.
I have added the the JavaScript version of my solution.
Full Contains Duplicate Solution
var containsDuplicate = function(nums) {
const uniqueSet = new Set(nums);
if(uniqueSet.size === nums.length) {
return false;
}
return true;
};
Obviously there are a lot of ways to solve the “Contains duplicate” problem. Like maybe you can use a loop (like, for, while etc) to check if there is any repeating values. But it will not be efficient. As for this kind of problem we should focus on finding the best solution.
Thanks again. In the next post, I will talk about another leetcode problem solution called Valid Anagram using JavaScript. Stay tuned.
Contains Duplicate | Leetcode problem Read More ยป