t2a20-leet-cohen.html


Prompt:Give me a beginner leet code question for me to solve.

Question: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.


My answer


var TwoSum = function(input, target) {
  let index = 0
  let resultArray = []
  for (index; index < input.length; index++){
    for (let element = index + 1; element < input.length; element++){
      if ((input[index] + input[element]) == target) {
        resultArray[0] = index
        resultArray[1] = element
        return resultArray
      }
    }
  }
    

ChatGPT answer


  function twoSum(nums, target) {
  const seen = new Map(); // store number -> index

  for (let i = 0; i < nums.length; i++) {
    const complement = target - nums[i];

    if (seen.has(complement)) {
      return [seen.get(complement), i];
    }

    seen.set(nums[i], i);
  }
}

Tester


Enter list of comma seperated values



Enter target number




...