Python || C++ || TypeScript
Brute Pressure Strategy
This strategy could be very easy, so I’m not going to waste a lot time on this strategy
- We take one aspect and examine it with all the opposite components.
- We do that for all the weather.
Code
def containsDuplicateMethod1(nums: record[int]) -> bool:
size = len(nums)
for i in vary(size):
for j in vary(i + 1, size):
if nums[i] == nums[j]:
return True
return False
Time Complexity: O(n^2)
House Complexity: O(1)
Higher Strategy utilizing Sorting
Since we now have to search out the duplicate components, so we will type the array after which discover the duplicate components.
Duplicate components will probably be adjoining to one another.
For instance: nums = [1, 2, 3, 1]
After sorting: nums = [1, 1, 2, 3]
Now we will discover the duplicate components by evaluating the adjoining components.
Code
def containsDuplicateMethod2(nums: record[int]) -> bool:
nums.type()
size = len(nums)
for i in vary(size - 1):
if nums[i] == nums[i + 1]:
return True
return False
Time Complexity: O(nlogn)
House Complexity: O(1)
Finest Strategy utilizing Hashing
This methodology can also be very straightforward to grasp.
- We create a Set.
- We traverse the array and test if the aspect is current within the Set or not.
- If the aspect is current within the Set then we return True.
- If the aspect is just not current within the Set then we add the aspect within the Set.
- If we traverse the entire array, and we do not discover any duplicate aspect then we return False.
Code
def containsDuplicateMethod3(nums: record[int]) -> bool:
storage = set()
for worth in nums:
if worth in storage:
return True
storage.add(worth)
return False
Time Complexity: O(n)
House Complexity: O(n)
Bonus
Finest Strategy utilizing Hashing (one liner)
def containsDuplicateMethod4(nums: record[int]) -> bool:
return len(nums) != len(set(nums))