0% completed
Solution: Contains Duplicate (easy)
Problem Statement
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.
Examples
Example 1:
Input: nums= [1, 2, 3, 4]
Output: false
Explanation: There are no duplicates in the given array.
Example 2:
Input: nums= [1, 2, 3, 1]
Output: true
Explanation: '1' is repeating.
Example 3:
Input: nums= [3, 2, 6, -1, 2, 1]
Output: true
Explanation: '2' is repeating.
Constraints:
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
.....
.....
.....
Shivam Badal
· 6 days ago
I did this at first, but when looking at the solution I saw the point of the exercise.
sset = set(nums) return False if len(sset) == len(nums) else True
Raúl Fiol
· a year ago
I just found another solution using Set(): by copying each element into a new set. Since a set only stores distinct elements, if the number of elements in the input matches the size of the Set, it means there are no duplicates
function containsDuplicate(nums) { if(!nums || nums.length == 0){ return false; } let nums_copy = new Set(); for(let i = 0; i<nums.length;i++){ nums_copy.add(nums[i]); } return nums_copy.size == nums.length ? false:true; }
mil o
· 2 years ago
Is there a reason why this would not be a good solution? Maybe I am overlooking something here
const uniqueSet = new Set(nums); if (uniqueSet.size !== nums.length) { return true; }
Jeana
· 2 years ago
The problem didnt call for an item not found in the set to be added into the set.
The problem simply states to return if the set contains duplicates or not. This is very weird to me.
Zachary Nelson
· 2 years ago
I appreciate that 3 example solutions are given but they are not given in order from least to most optimal. It would be nice to at least callout which solution for problems is the most optimal solution.
raol buqi
· 2 years ago
in the article you wrote set.count(x), set doesn't have a count method
Abhijit Gupta
· 2 years ago
The count operation on a HashSet does not make sense. Please check this line -
set.count(x) also has an average time complexity of O(1)."
Anonymous
· 2 years ago
I'm confused why would the worst case scenario for approach 2 be O(n^2) when using a Set in JavaScript since if the number already exists in the set, the add operation would just be ignored and the code would just early return true? So shouldn't the worst case scenario for approach 2 still be O(n)?
ethanedge
· 2 years ago
The explanation uses the variable name 'unique_set' but in the Java code solution it is called just 'set'.
Calvin
· 3 years ago
def containsDuplicate(nums): for i in range(len(nums)): if nums[i] in nums[1+i:]: return True return False
Reading Progress
0%