Two Integers Sum to Target Sum

Given a list of integers and a target sum, this problem determines whether any two integers in the list sum to the target sum. For example, given the input [1, 2, 3 , 4, 5] and target sum = 9, the output would be true because 4 + 5 = 9.

Problem

Given a list of integers and a target sum, determine whether any two integers in the list sum to the target sum.
Example input: [1, 2, 3, 4, 5], target sum = 9
Example output: true (because 4 + 5 = 9)

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:
// This solution is optimal because it uses a hash table to store the values of the array.
// This allows us to check if the complement of the current value is in the hash table.
// If it is, then we have found a pair that sums to the target sum.
// This solution is O(n) time complexity and O(n) space complexity.

function twoSum(arr, target) {
  const hash = {};
  for (let i = 0; i < arr.length; i++) {
    const complement = target - arr[i];
    if (hash[complement]) {
      return true;
    }
    hash[arr[i]] = true;
  }
  return false;
}

console.log(twoSum([1, 2, 3, 4, 5], 9)); // true
console.log(twoSum([1, 2, 3, 4, 5], 10)); // false

A.I. Evaluation of the Solution

The candidate's solution is correct and demonstrates a level of completeness. The solution uses a hash table to store the values of the array, which allows for checking if the complement of the current value is in the hash table. If it is, then the candidate has found a pair that sums to the target sum. The solution has a time complexity of O(n) and a space complexity of O(n).

Evaluated at: 2022-11-20 18:15:32