Contains Duplicate

Problem

Given an integer array nums, return true if any value appears more than once in the array, otherwise return false.

Examples

Example 1:

Input: nums = [1, 2, 3, 3]

Output: true

Example 2:

Input: nums = [1, 2, 3, 4]

Output: false

Constraints

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

You should aim for a solution with O(n) time and O(n) space, where n is the size of the input array.

Solution

Iterate, store in a set and check if we’ve seen.

class Solution {
public:
    bool hasDuplicate(vector<int>& nums) {
        std::unordered_set<int> items;
        for (const auto &num : nums) {
            if (items.contains(num)) {
                return true;
            }
            items.insert(num);
        }
        return false;
    }
};