LeetCode 217: Contains Duplicate
Have you ever looked at a list of names and wondered if someone's name appears twice? Maybe you're checking a guest list for a party or a list of IDs in a database. That's exactly what this problem asks us to do with an array of integers. π§
π§© The Problem
Given an integer array
nums, returntrueif any value appears at least twice in the array, and returnfalseif every element is distinct.
Examples
Example 1:
Input: nums = [1,2,3,1]
Output: true
Explanation: The element 1 occurs at indices 0 and 3. β
Example 2:
Input: nums = [1,2,3,4]
Output: false
Explanation: All elements are distinct. β
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
Constraints
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
π§ How to Think About This
We need to check if there are any repeating numbers. There are three common ways to solve this, each with its own trade-offs:
1. Brute Force (Check everything)
Compare every pair of numbers.
- Logic: For each number, look at every other number.
- Time: β Too slow for large arrays. π’
- Space: .
2. Sorting (Order them up)
If we sort the array, any duplicates will be right next to each other.
- Logic: Sort
[1, 3, 2, 1]β[1, 1, 2, 3]. Now check ifnums[i] == nums[i+1]. - Time: β Pretty good! ποΈ
- Space: or depending on the sorting algorithm.
3. Hash Set (The Memory Trick)
Use a "notebook" (Set) to remember numbers we've seen.
- Logic: As we walk through the array, check if the current number is in our set. If it is, we found a duplicate! If not, add it to the set and move on.
- Time: β Optimal! π
- Space: β We need extra memory for the set.
π Visualizing the Hash Set Approach
nums = [1, 2, 3, 1]
seen = set()
1. Current: 1 | Is 1 in seen? No. | Add 1 to seen β {1}
2. Current: 2 | Is 2 in seen? No. | Add 2 to seen β {1, 2}
3. Current: 3 | Is 3 in seen? No. | Add 3 to seen β {1, 2, 3}
4. Current: 1 | Is 1 in seen? YES! | Return True π
π» Solution (Hash Set)
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
# We use a set for O(1) average time complexity lookups
seen = set()
for num in nums:
# If we've seen this number before, we found a duplicate
if num in seen:
return True
# Otherwise, record that we've seen it
seen.add(num)
# If we finish the loop, all numbers are unique
return FalseResults
Runtime: 17 ms β Beats 66.43%
Memory: 25.73 MB β Beats 77.93%
β±οΈ Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Brute Force | ||
| Sorting | or | |
| Hash Set |
The Hash Set approach is generally preferred in interviews because it gives us the best time complexity, and space is usually acceptable.
β οΈ Common Mistakes
- Using a List instead of a Set β If you do
seen = []andif num in seen:, the lookup becomes , making your total time complexity . Always use a Set for lookups! - Returning too early β Make sure you only return
Falseafter the entire loop finishes. - Overcomplicating with a Hash Map β You don't need to count the frequencies; just knowing if it exists once is enough. A Set is cleaner than a Map/Dictionary here.
π§ How to Recognize This Pattern
When you see these keywords in an interview:
- "at least twice"
- "distinct"
- "duplicate"
- "unique"
Think:
HASH SET or SORTING
π― Interview Tips
- Mention the Trade-offs β "I can solve this in time with space using sorting, or time with space using a hash set. Which would you prefer?"
- One-liner Trick β In Python, you can also solve this in one line:
return len(nums) != len(set(nums)). However, the loop approach is often better because it can early return as soon as it finds the first duplicate! - Constraints Matter β If the array is very large and memory is tight, sorting might be better than a hash set.
- Explain the Set β Briefly explain why a set is fast ( average time for searching).
