Skip to content

Instantly share code, notes, and snippets.

@visionbyangelic
Created December 27, 2025 12:07
Show Gist options
  • Select an option

  • Save visionbyangelic/c4de80c4eca261b46ee083dbbcdf696e to your computer and use it in GitHub Desktop.

Select an option

Save visionbyangelic/c4de80c4eca261b46ee083dbbcdf696e to your computer and use it in GitHub Desktop.

217 | Contains Duplicate πŸ‘―β€β™‚οΈ - Leetcode Day 2

The Challenge: Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

πŸ’‘ The "Aha!" Moment

Initially, I thought about comparing every number against every other number (Brute Force), but that is too slow for large lists. I realized I didn't need to check everyone against everyone; I just needed a way to remember what I had already seen. If I see a number that is already in my "memory," I know immediately it is a duplicate.

πŸ› οΈ My Strategy: The "Bouncer" Set

  • Data Structure: I used a Hash Set (seen = set()).
  • Mechanism: I treated the Set like a bouncer at a club with a perfect memory.
  • Logic: As I iterate through the list, I ask the Set, "Is this number already inside?"
    • Yes: Stop immediately! We found a duplicate. Return True.
    • No: Add the number to the Set and keep moving.

🐍 Python Implementation

class Solution(object):
    def containsDuplicate(self, nums):
        # Create an empty set to store numbers we have seen
        seen = set()
        
        # Loop through each number in the input array
        for num in nums:
            # Check if the number is already in our set
            if num in seen:
                return True
            
            # If not, add it to the set
            seen.add(num)
            
        # If we finish the loop, no duplicates exist
        return False

πŸ“Š Performance Reflection

Time Complexity: $O(N)$ β€” We iterate through the list exactly once.

Space Complexity: $O(N)$ β€” In the worst case (no duplicates), we store every number in the Set.


βœ… Proof of Acceptance :

image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment