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).
