#9EasyArrays & Hashing

Contains Duplicate

Given an integer array `nums`, return `true` if any value appears at least twice, or `false` if every element is distinct. **Core Insight:** The simplest correct approach uses a hash set. As we iterate through the array, we try to insert each element into the set. If the element is already present, we have found a duplicate and return `true` immediately. If we finish the loop without finding one, we return `false`. **Algorithm:** Create an empty set. For each `num` in `nums`: if `num` is in the set return `true`, otherwise add `num` to the set. Return `false` after the loop. **Alternative:** Sort the array first (O(n log n)) and check adjacent elements — but the hash set approach is faster at O(n) time. **Complexity:** Time O(n) — one pass, each hash set operation is O(1) average. Space O(n) — the set holds at most n elements.

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹
Solution inPython
Python
def containsDuplicate(nums: list[int]) -> bool:
    return len(nums) != len(set(nums))