150NeetCode 150

1.Contains Duplicate

EasyBlind 75Arrays & Hashing ยท 1/9

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.

Examples

Input:  nums = [1, 2, 3, 1]
Output: true
Explanation: The value 1 appears at index 0 and index 3.
Input:  nums = [1, 2, 3, 4]
Output: false
Explanation: Every element is distinct.
Input:  nums = [1, 1, 1, 3, 3, 4, 3, 2, 4, 2]
Output: true

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

๐Ÿ’ก Key Insight

We only need to know whether we have seen a value before. Comparing every pair is slow, sorting puts duplicates next to each other, and a hash set answers "have I seen this?" in O(1) โ€” so a single pass is enough.

Brute Force

TimeO(nยฒ)SpaceO(1)

Intuition

Compare every element with every element that comes after it. If any pair is equal, we found a duplicate.

Algorithm

  1. For each index i from 0 to n - 1:
  2. For each index j from i + 1 to n - 1:
  3. If nums[i] == nums[j], return true.
  4. If no pair matched, return false.

Visualization

nums = [1, 2, 3, 1]

i=0 (1): compare with 2 โœ—, 3 โœ—, 1 โœ“  โ†’ return true

Code

java
class Solution {
    public boolean containsDuplicate(int[] nums) {
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (nums[i] == nums[j]) {
                    return true; // found a pair of equal values
                }
            }
        }
        return false;
    }
}

Complexity

  • Time: O(nยฒ) โ€” every pair (i, j) is checked once.
  • Space: O(1) โ€” no extra data structures.

Complexity Comparison

Approach Time Space
Brute Force O(nยฒ) O(1)
Sorting O(n log n) O(1)โ€“O(n)
Hash Set O(n) O(n)

Common Pitfalls

  • Using List.contains instead of a Set โ€” that makes each lookup O(n) and the whole solution O(nยฒ).
  • Sorting modifies the input array; mention this trade-off if the caller needs the original order.
  • Forgetting that nums can contain negative numbers โ€” a fixed-size boolean array indexed by value will not work.
  • Returning early with false inside the loop โ€” you can only conclude "no duplicates" after scanning everything.