Our first LeetCode problem! 🎉 This is LeetCode #217: Contains Duplicate.
Given an integer array nums, return True if any value appears at least twice, and False if every element is distinct.
Approach 1: Brute Force — O(n²)
Compare every pair. Works but slow.
Approach 2: Using a Set — O(n)
A set only stores unique values. If we try to add something that already exists, we found a duplicate!
💭 Time to code! Use the step-by-step approach described above. Don't peek at the solution — try first! 🚀
Approach 3: One-liner
If the set is smaller than the list, there must be duplicates.
Complexity: Time O(n), Space O(n) — we store up to n elements in the set.
# Optimal solution — O(n) time, O(n) space
def containsDuplicate(nums):
seen = set()
for num in nums:
if num in seen: # O(1) lookup!
return True
seen.add(num)
return False
containsDuplicate([1, 2, 3, 1])
True
containsDuplicate([1, 2, 3, 4])
False
containsDuplicate([1, 1, 1, 3, 3, 4])
True