Question Link: https://leetcode.com/problems/contains-duplicate/description/
So, I was able to quickly solve this problem with an approach of Sorting. O(n log n) time complexity.
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
nums.sort()
for i in range(0, len(nums)):
if (i+1) < len(nums):
if nums[i] == nums[i+1]:
return True
return False
Now, one point I missed while thinking about the approach was that i+1 can go out of range if there are no duplicates.
There are other possible methods to solve this too. 4 were listed in the solution of this question.
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
for i in range(0, len(nums)):
for j in range(i+1, len(nums)):
if nums[i] == nums[j]:
return True
return False
The one I used
This is a better approach it only takes time O(n) however it has O(n) space complexity too.
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
visited = set()
for i in nums:
if i in visited:
return True
visited.add(i)
return False
This one was similar to the above one time and everything same. Just used a dictionary, i.e., hash map instead of set.
Could be more useful when finding duplicate occurrences.