GitHub
Easy

Contains Duplicate

Given an integer array, determine if any value appears at least twice in the array.

Write a function that returns true if any value appears at least twice in the array, and false if every element is distinct.

How to Solve

Use a Set to track seen numbers. As you iterate through the array, if a number is already in the set, return true. Otherwise, add it to the set. If you finish iterating without finding duplicates, return false.

Code

Test Cases

Input 1

Expected Output: true (1 appears twice)

Input 2

Expected Output: false (all elements are distinct)

Input 3

Expected Output: true (multiple duplicates exist)

Complexity

Time Complexity: O(n) - We iterate through the array once, and Set operations (add, has) are O(1) on average.

Space Complexity: O(n) - In the worst case, the Set stores all n elements before finding a duplicate.