Contains Duplicate

Problem:

Given an integer array nums, return true if any value appears more than once in the array, 
otherwise return false.

Example 1:
Input: nums = [1, 2, 3, 3]
Output: true

Example 2:
Input: nums = [1, 2, 3, 4]
Output: false

Description

A set, by definition, is a collection of distinct elements. This property makes it an ideal tool for tracking unique items. By using a set to store elements, you can efficiently detect duplicates. When adding a new element to the collection, you can quickly determine if it already exists in the set. If it does, that means you've encountered a duplicate item.

Logic

  • For each number in the list
    • Before adding a new number to the set, check if the number exists in the set. If so, we know a duplicate is found.

Solution

class Solution(object):
    @staticmethod
    def containsDuplicate(nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        unique_elements = set()

        for num in nums:
            if num in unique_elements:
                return True
            unique_elements.add(num)
        
        return False
        
Solution.containsDuplicate([1, 2, 3, 1]) # True
Solution.containsDuplicate([1, 2, 3]) # False
Solution.containsDuplicate([1, 2, 9, 11, 12, 31, 1]) # True
Solution.containsDuplicate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) # False