Determining If a Pair of Integers in an Array Sums to a Target Value

Given an array of integers and a target value, this problem asks if there is a pair of integers in the array that sums to the target value. An example input and output are given.

Problem

Given an array of integers and a target value, determine if there is a pair of integers in the array that sums to the target value.
Example input: [3, 5, 2, -4, 8, 11], 7
Example output: True (3 + 4 = 7)

Solution

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

using namespace std;

bool sum_exists(vector<int>& arr, int target) {
    unordered_map<int, int> map;
    for (int i = 0; i < arr.size(); i++) {
        if (map.find(arr[i]) != map.end()) {
            return true;
        }
        map[target - arr[i]] = i;
    }
    return false;
}

int main() {
    vector<int> arr = {3, 5, 2, -4, 8, 11};
    int target = 7;
    cout << sum_exists(arr, target) << endl;
    return 0;
}

A.I. Evaluation of the Solution

The candidate's solution is complete and solves the problem. The candidate has used a hash map to store the complement of each number in the array. If the complement exists in the hash map, then the candidate returns true. Otherwise, the candidate adds the current number and its index to the hash map.

Evaluated at: 2022-12-01 08:15:35