LeetCode 217 - Contains Duplicate
2026-04-01
easy array
Given an integer array nums, return true if any value appears more than once in the array, otherwise return false.
Example 1:
python
Input: nums = [1, 2, 3, 3]
Output: trueExample 2:
java
Input: nums = [1, 2, 3, 4]
Output: falseSolution 1:
python
class Solution:
def hasDuplicate(self, nums: List[int]) -> bool:
# we can use set and check the length, because set don't allow duplicate
# time complexity is O(n) since it need to transfer to set
# space complexity also is O(n) because it need space for set
return len(set(nums)) != len(nums)Solution 2:
python
class Solution:
def hasDuplicate(self, nums: List[int]) -> bool:
# Hash Set Solution
# Time Complexity: O(n) in the worst case. However, it leverages an "early exit"
# (short-circuiting) mechanism, returning True immediately upon finding a match.
# Space Complexity: O(n) in the worst case, as the set will store all elements
# if the array contains entirely unique integers.
duplicate_set = set()
for i in nums:
if i in duplicate_set:
return True
else:
duplicate_set.add(i)
return False