Pair Sums to Target Value

This function takes in a set of integers and a target value, and returns true if there is a pair of integers in the set that sum up to the target value. Otherwise, it returns false.

Problem

Given a set of integers, write a function that returns true if there exists a pair of integers in the set that sum up to a given target value. Return false otherwise.
Example input: [3, 5, 2, -4, 8, 11], target = 7
Example output: true (5 + 2 = 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>& v, int target) {
    unordered_map<int, int> m;
    for (int i = 0; i < v.size(); i++) {
        if (m.find(v[i]) != m.end()) {
            return true;
        }
        m[target - v[i]] = v[i];
    }
    return false;
}

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

A.I. Evaluation of the Solution

The candidate's solution is complete and solves the problem. The approach is to use a hash map to store the complement of each number in the array. If the complement exists in the hash map, then a pair exists that sums up to the target value.

Evaluated at: 2022-12-09 10:15:30