Table of Contents
Problem Statement:
Contains Duplicate LeetCode Solution says that- 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
Example 3:
Input:
nums = [1,1,1,3,3,4,3,2,4,2]
Output:
true
Constraints:
1 <= nums.length <= 10
5-10
9<= nums[i] <= 10
9
Algorithm –
Idea –
- In order to find the Contains Duplicate. What will we do in this question? At first, we will focus on the duplicate element, and after seeing the duplicate element. we will simply return True and if the array doesn’t contain duplicates then we will Return False.
- At first, we will create one HashSet after that we will traverse the whole array and check for the condition that if the element is present in the set then we will return True else we will add that element into the Set.
Approach –
- Create one Hash-set for an efficient solution.
- Iterate the whole loop from 0 to len(nums).
- Check for the Condition that if the element is present in the set then we will return True.
- Else if not Present then we will add that element into the set.
- After traversing the whole array if it doesn’t return True, then finally we will return False after iterating the whole array.
- Hence we will check the Contain Duplicate.
Image of Contain Duplicate-
class Solution { public boolean containsDuplicate(int[] nums) { Set<Integer> s = new HashSet<Integer>(); for(int i : nums){ if (s.contains(i)){ return true; } else{ s.add(i); } } return false; } }
class Solution: def containsDuplicate(self, nums: List[int]) -> bool: s = set() for i in nums: if i in s: return True else: s.add(i) return False
Complexity Analysis for Contains Duplicate LeetCode Solution:
Time complexity: O(N), As we have traversed through the whole array only one time.
Space complexity: O(N), As we have created one Hash set.
SIMILAR QUESTION – https://tutorialcup.com/interview/hashing/contains-duplicate.htm