Two Sum

Given an array of integers and a target value, return the indices of the two array elements that add up to the target value. Assume that each input will have only one solution, and that the same array element cannot be used twice.

Problem

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [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 and their indices.
// This way, we can check if the complement of the current number is in the hash table.
// If it is, we can return the indices of the current number and the complement.
// This solution is optimal because it is O(n) time complexity and O(n) space complexity.

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

console.log(twoSum([2, 7, 11, 15], 9));

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, using a hash table to store the numbers and their indices. This solution is optimal because it is O(n) time complexity and O(n) space complexity.

Evaluated at: 2022-12-10 02:15:34