🎢 ELI5 Park / Arrays & Hashing / Contains Duplicate
Easy

Contains Duplicate

👶 The 5-Year-Old Summary

You're playing with your toys and someone asks "Do you have two of the same toy?" You quickly glance through your toys to see if any of them appear twice!

🎮 Interactive Visualizer

Click "Step" to see if we find any duplicates!

Set (unique toys we've seen):

🧠 The Brain Hack

When asked "does this contain duplicates?", always think Set or Hash Map! If adding to a set fails (already exists), you found a duplicate!

💻 The Clean Solution

def contains_duplicate(nums):
    # A box to hold unique toys we've seen
    seen = set()
    
    # Check each toy one by one
    for num in nums:
        # Have we seen this toy before?
        if num in seen:
            # Found a duplicate!
            return True
        
        # Put this toy in our box
        seen.add(num)
    
    # No duplicates found
    return False

# Try it!
nums = [1, 2, 3, 1]
print(contains_duplicate(nums))  # Output: True

nums2 = [1, 2, 3, 4]
print(contains_duplicate(nums2))  # Output: False

Time: O(n) - We check each number once!

Space: O(n) - Worst case, we store all unique numbers.