Check If an Array Contains Any Duplicate

Implement containsDuplicate

Given an array nums, return true if any value appears at least twice, and false if every element is distinct. Checking every pair works but revisits the same information repeatedly. A hash setHash SetA collection that supports checking whether a value is present, and adding a new value, both in average O(1) time — no scanning required. remembers every value seen so far, so each new number only needs a single O(1) lookup to know whether it's already appeared — turning the O(n²) comparison into a single O(n) pass.

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

+ 8 hidden test cases run on Submit.

Constraints:

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹

nums =

[1, 2, 3, 1]