DSA problem
Contains Duplicate
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.
This is a classic introductory hash table problem. A brute-force solution compares every pair of elements in O(n^2) time. The optimal solution trades space for time: by tracking which values have already been seen in a hash set, each element can be checked in constant time, reducing the overall runtime to a single linear pass over the array.
Examples
Example 1
Input:
nums = [1,2,3,1]Output:
trueExplanation: The value 1 appears at index 0 and index 3, so the array contains a duplicate.
Example 2
Input:
nums = [1,2,3,4]Output:
falseExplanation: All four elements are distinct, so there is no duplicate.
Example 3
Input:
nums = [1,1,1,3,3,4,3,2,4,2]Output:
trueExplanation: Several values repeat (for example 1, 3, 4, and 2), so the result is true.
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.