loading

Contains Duplicate — Step-by-Step Visualization

easyLeetCode #217ArrayHash TableSorting

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.

Algorithm Pattern

Hash Set Membership

Key Idea

We use a Hash Set to store every number we visit as we iterate through the array. For each number, we check if it is already in the set. If it is, we found a duplicate and return `True`. If we finish the entire array without finding a duplicate, we return `False`. This approach takes O(n) time and O(n) space.

Step-by-Step Approach

  1. Initialize an empty `seen` set.
  2. For each number `n` in `nums`:
  3. If `n` is in `seen`, return `True`.
  4. Add `n` to `seen`.
  5. Return `False`.

Common Gotchas

  • Using a set is much faster than checking every pair of numbers (O(n²)).
  • Sorting the array first (O(n log n)) and checking adjacent elements is another option if space is critical.

Related Problems