Skip to content

217. Contains Duplicate 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  bool containsDuplicate(vector<int>& nums) {
    unordered_set<int> seen;

    for (const int num : nums)
      if (!seen.insert(num).second)
        return true;

    return false;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
  public boolean containsDuplicate(int[] nums) {
    Set<Integer> seen = new HashSet<>();

    for (final int num : nums)
      if (!seen.add(num))
        return true;

    return false;
  }
}
1
2
3
class Solution:
  def containsDuplicate(self, nums: list[int]) -> bool:
    return len(nums) != len(set(nums))