Given an integer array nums, return true if any value appears more than once in the array, otherwise return false.
Example 1:
Input: nums = [1, 2, 3, 3] Output: true
Example 2:
Input: nums = [1, 2, 3, 4] Output: false
Naive solution to loop through the list
and checking the dictionary on each loop. Breaking when there is a duplicate with expected value True
.
O(n)
O(n)
class Solution: def hasDuplicate(self, nums: List[int]) -> bool: result = False checkDict = {} for i in nums: if checkDict.get(i) == None: checkDict[i] = i else: result = True break return result
Building set
data structure to detect duplicates:
O(n)
O(n)
class Solution: def hasDuplicate(self, nums: List[int]) -> bool: hashset = set() for n in nums: if n in hashset: return True hashset.add(n) return False
Comparing the length of original array and set created from the original array:
O(n)
set
, so O(n)
O(n)
set
, so O(n)
worst caseclass Solution: def hasDuplicate(self, nums: List[int]) -> bool: return len(set(nums)) < len(nums)