Contains Duplicate - Problem

You're given an array of integers, and your task is to determine if any number appears more than once. This is a fundamental problem that tests your ability to efficiently detect duplicates in a dataset.

Goal: Return true if any value appears at least twice in the array, and false if every element is unique.

Example: In the array [1, 2, 3, 1], the number 1 appears twice, so we return true. But in [1, 2, 3, 4], all elements are distinct, so we return false.

This problem appears frequently in coding interviews and has multiple solution approaches with different time and space trade-offs. Master this problem to build a strong foundation in hash tables, sorting, and array manipulation!

Input & Output

example_1.py — Basic Duplicate
$ Input: [1,2,3,1]
Output: true
💡 Note: The value 1 appears at indices 0 and 3, so we return true since there's a duplicate.
example_2.py — No Duplicates
$ Input: [1,2,3,4]
Output: false
💡 Note: All elements are distinct (1, 2, 3, 4), so we return false as no duplicates exist.
example_3.py — Multiple Duplicates
$ Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
💡 Note: Multiple duplicates exist: 1 appears 3 times, 3 appears 3 times, 4 appears 2 times, and 2 appears 2 times. We return true upon finding the first duplicate.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • Note: The array can contain both positive and negative integers

Visualization

Tap to expand
Hash Set vs Brute Force: A Bouncer's PerspectiveBRAINGuestHash Set BouncerO(1) recognition"I remember everyone!"Guest List:1. John2. Mary3. Bob4. Alice5. ...GuestBrute Force BouncerO(n) list scanning"Let me check my list..."Performance ComparisonHash Set: O(n) totalBrute Force: O(n²) total
Understanding the Visualization
1
Bouncer with perfect memory (Hash Set)
Remembers every face instantly - O(1) recognition time per person
2
Bouncer with written list (Brute Force)
Must scan entire list for each person - O(n) time per person
3
The result
Hash set approach is dramatically faster for large crowds
Key Takeaway
🎯 Key Insight: Hash sets provide O(1) average lookup time, making them perfect for duplicate detection. Like a bouncer with perfect memory, they recognize duplicates instantly!
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28 Apple 25
128.5K Views
Very High Frequency
~15 min Avg. Time
3.2K 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