Contains Duplicate - Problem

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 fundamental problem that tests your understanding of data structures and algorithms for detecting duplicates efficiently.

Input & Output

Example 1 — Contains Duplicate
$ Input: nums = [1,2,3,1]
Output: true
💡 Note: The value 1 appears at both index 0 and index 3, so there is a duplicate.
Example 2 — All Distinct
$ Input: nums = [1,2,3,4]
Output: false
💡 Note: All elements are distinct, no duplicates found.
Example 3 — Multiple Duplicates
$ Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
💡 Note: Several values appear multiple times (1, 2, 3, and 4), so there are duplicates.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Contains Duplicate - Hash Set Approach INPUT Integer Array: nums 1 idx 0 2 idx 1 3 idx 2 1 idx 3 Duplicate Found! Input: nums = [1, 2, 3, 1] Length: 4 elements Value 1 appears twice ALGORITHM STEPS 1 Create Hash Set Empty set to track seen values 2 Iterate Array Check each element once 3 Check if in Set If yes, return true 4 Add to Set Otherwise, add element Hash Set Progress: i=0: set={1} i=1: set={1,2} i=2: set={1,2,3} i=3: 1 in set? YES! --> return true FINAL RESULT true Duplicate Exists Output: true Verification: Value 1 found at index 0 Value 1 found at index 3 Same value appears twice Result: OK - Contains Dup Time: O(n) | Space: O(n) Key Insight: Hash Set provides O(1) lookup time. Instead of comparing every pair (O(n^2)), we check if each element exists in our set before adding it. If found, we have a duplicate immediately. Trade-off: O(n) extra space for optimal O(n) time complexity. TutorialsPoint - Contains Duplicate | Hash Set - Optimal Solution
Asked in
Google 25 Amazon 30 Microsoft 20 Apple 15
125.0K Views
High Frequency
~15 min Avg. Time
3.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen