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.
- Yes: Stop immediately! We found a duplicate. Return
π 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:
Space Complexity:
β Proof of Acceptance :