20 March 2024

Easy

1. Two Sum

Link: https://leetcode.com/problems/two-sum

Description: Given an array of integers, return indices of the two numbers such that they add up to a specific target.

First solution:

Iterate over array and for each number, calculate difference between target and number. Then find index of difference in array. If index is found and it is not the same as current index, return both indexes.

var twoSum = function (nums, target) {
  for (let i = 0; i <= nums.length; i++) {
    const first = nums[i]
    const diff = target - first
    const indexOfSecond = nums.indexOf(diff)
    if (indexOfSecond > -1 && indexOfSecond !== i) {
      return [i, indexOfSecond]
    }
  }
}

Second solution:

Create object to store as key number and as value index. Iterate over array and for each number, calculate difference between target and number. If difference is found as key in object, return both indexes.

var twoSum = function (nums, target) {
  const obj = {}

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

Second solution is faster than first one.