Determining if an Array Contains Duplicates

This problem asks you to write a function that takes in an array of integers and returns true if any element appears more than once in the array. Otherwise, the function should return false.

Problem

Given an array of integers, write a function that determines whether the array contains any duplicates. Your function should return true if any element appears more than once in the array, and false if every element is unique.
Example input: [1, 2, 3, 4, 5]
Example output: false
Example input: [1, 2, 3, 4, 4]
Example output: true

Solution

This solution is in C++. Our A.I. can create solutions in multiple languages.
by kayakane
#include <iostream>
#include <vector>
#include <unordered_set>

using namespace std;

bool containsDuplicates(vector<int>& nums) {
    unordered_set<int> set;
    for (int i = 0; i < nums.size(); i++) {
        if (set.find(nums[i]) != set.end()) {
            return true;
        }
        set.insert(nums[i]);
    }
    return false;
}

int main() {
    vector<int> nums1 = {1, 2, 3, 4, 5};
    vector<int> nums2 = {1, 2, 3, 4, 4};
    cout << containsDuplicates(nums1) << endl;
    cout << containsDuplicates(nums2) << endl;
    return 0;
}

A.I. Evaluation of the Solution

This is a great solution! The candidate has used a hash set to keep track of unique elements in the array as they iterate through it. This is an efficient way to solve the problem with a time complexity of O(n).

Evaluated at: 2022-11-27 16:15:28