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.

Constraints:

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Examples:

Example 1:

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

Example 2:

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

Example 3:

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

Solution

Approach 1: Using a Hash Set

This is the most efficient approach for checking duplicates.

  • Initialize a hash set (or set in Python): This set will store unique elements encountered so far.
  • Iterate through the array: For each num in nums:
    • Check for existence: If num is already in the hash set, it means we've encountered this number before. A duplicate exists, so return true.
    • Add to set: If num is not in the hash set, add it to the set.
  • No duplicates found: If the loop completes without returning true, it means no duplicates were found, so return false.

Time Complexity: O(N) on average, where N is the number of elements in nums, because hash set operations (insertion and lookup) take average O(1) time. Space Complexity: O(N) in the worst case, as the hash set might store all unique elements.

Approach 2: Sorting (Alternative)

  • Sort the array: Use an efficient sorting algorithm.
  • Iterate and compare adjacent elements: After sorting, duplicates will be adjacent. Iterate from the first element up to the second-to-last element. If nums[i] == nums[i+1], a duplicate is found, return true.
  • No duplicates found: If the loop completes, return false.

Time Complexity: O(N log N) due to sorting. Space Complexity: O(1) or O(log N) depending on the sorting algorithm used (in-place sort vs. auxiliary space for quicksort/mergesort recursion stack).

class Solution:
    def containsDuplicate(self, nums: list[int]) -> bool:
        seen = set() # Initialize a hash set
        for num in nums:
            if num in seen: # Check if the number has been seen before
                return True # Duplicate found
            seen.add(num) # Add the current number to the set
        return False # No duplicates found after checking all elements

# Example Usage:
# sol = Solution()
# print(sol.containsDuplicate([1,2,3,1])) # Expected: True
# print(sol.containsDuplicate([1,2,3,4])) # Expected: False
# print(sol.containsDuplicate([1,1,1,3,3,4,3,2,4,2])) # Expected: True