Two Sum

Given an array of integers and a target value, return the indices of the two numbers in the array that add up to the target value.

Problem

Given an array of integers, return the indices of the two numbers such that they add up to a specific target.
Input: [2, 7, 11, 15], target = 9
Output: [0, 1]

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:
// The optimal solution is to use a hash table to store the numbers in the array as keys and their indices as values.
// Then, we can iterate through the array and check if the target minus the current number is in the hash table.
// If it is, we return the indices of the current number and the target minus the current number.
// This solution is optimal because it has a time complexity of O(n) and a space complexity of O(n).

function twoSum(nums, target) {
  const hashTable = {};
  for (let i = 0; i < nums.length; i++) {
    hashTable[nums[i]] = i;
  }
  for (let i = 0; i < nums.length; i++) {
    const complement = target - nums[i];
    if (hashTable[complement] && hashTable[complement] !== i) {
      return [i, hashTable[complement]];
    }
  }
}

console.log(twoSum([2, 7, 11, 15], 9)); // [ 0, 1]
console.log(twoSum([3, 2, 4], 6)); // [1, 2]
console.log(twoSum([3, 3], 6)); // [0, 1]

A.I. Evaluation of the Solution

The candidate's solution is correct and demonstrates a level of completeness. The candidate's approach is also correct. The candidate's solution has a time complexity of O(n) and a space complexity of O(n).

Evaluated at: 2022-11-25 04:16:04