š© Contains Duplicate (#217)
š Problem Linkā
š Problem Statementā
Given an integer array nums, return true if any value appears more than once in the array, otherwise return false.
š” Examplesā
Example 1ā
Input: nums = [1,2,3,1]
Output: true
Example 2ā
Input: nums = [1,2,3,4]
Output: false
š Key Insights & Approachā
Core Observation: If we've seen a number before while iterating through the array, we immediately have a duplicate ā no need to continue checking.
Why Hash Set/Table?
- Checking membership:
O(1)average time - Beats sorting
O(n log n)or nested loopsO(n²)
Two Solution Approaches:
- Length comparison:
len(nums) != len(set(nums))- simple one-liner - Early exit: Track seen elements, return immediately on first duplicate - more efficient
This is the "Have we seen this before?" pattern:
- Useful for: duplicates, two sum, first repeated element
- Trade-off:
O(n)extra space forO(n)time
š Solution: Pythonā
Approach 1: Using Setā
Time Complexity: O(n) | Space Complexity: O(n)
def contains_duplicate(nums):
return len(nums) != len(set(nums))
Approach 2: Using Hash Tableā
Time Complexity: O(n) | Space Complexity: O(n)
def contains_duplicate(nums):
seen = set()
for num in nums:
if num in seen:
return True
seen.add(num)
return False
šµ Solution: Golangā
Approach 1: Using Map/Setā
Time Complexity: O(n) | Space Complexity: O(n)
func containsDuplicate(nums []int) bool {
hashTable := make(map[int]bool)
for _, num := range nums {
if _, ok := hashTable[num]; ok {
return true
}
hashTable[num] = true
}
return false
}