- Link: 217. Contains Duplicate
- Track: NeetCode150
Question
Example 1
- Input: nums =
[1,2,3,1] - Output: true
- Explanation: The element 1 occurs at the indices 0 and 3.
Restate the problem
- Given an integer array nums
- Return True if any value appears at least twice, otherwise return False.
Edge Case
[], return Falselen(nums)< 2, return False
| Method | Approach | Time Complexity | Space Complexity |
|---|---|---|---|
| Method 1 ⭐ | Hashmap | O(n) | O(n) |
| Method 2 | Sort | O() | O(1) |
Method 1: HashSet
Approach
- Initial an empty set
seen(only stores unique values) - Scan the
nums - If
numinseen, return True- Add num into set
Complexity
- Time Complexity: O(n)
- Space Complexity: O(n)
Code
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
seen = set()
for num in nums:
if num not in seen:
seen.add(num)
else:
return True
return FalseMethod 2: Sort + Scan
Approach
- Sort
nums - Scan sorted
nums, start from 1- If the current number equals the previous number, return
True
- If the current number equals the previous number, return
Complexity
- Time Complexity: O()
- Sorting:
- Space Complexity: O(1)
Code
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
nums.sort()
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
return True
return FalseHistory
- Feb-27-2026 Solved
- Jan-15-2026 Solved