DEV Community

OlumideSamuel
OlumideSamuel

Posted on

The infamous Two Sum problem. (DSA Series 3)

Problem

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.

  • Example
  • Input: nums = [2,7,11,15], target = 9
  • Output: [0,1]
  • Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
  • Input: nums = [3,2,4], target = 6
  • Output: [1,2]
  • Input: nums = [3,3], target = 6
  • Output: [0,1]

Solution

  • THIS WILL ONLY WORK IF ITEMS ARE SORTED
  • let there be two pointers, one point to the beginning of array (low), and the other to the end of array (high).
  • while low < high,
  • if the sum of the value at low and high = target, return the indices
  • if the sum of the values at low and high > target, reduce high index by 1
  • if the sum of the values at low and high < target, increase the low by 1
function twoSum(array, target){
    let low = 0;
    let high = array.length - 1;

    while (low < high) {
        const sum = array[low] + array[high];
        if (sum === target) return [low, high];
        if (sum > target) high--;
        else if (sum < target) low++;
    }
}
Enter fullscreen mode Exit fullscreen mode

Method Two

/**
 * 
 * Input: nums = [2,7,11,15], target = 9 
 * Output: [0,1]
 * Initialize a map,
 * loop through array, 
 * subtract currentItem from target to get compliment, 
 *  if compliment exist in map, return [currentItmIdx, compliment[]]
 * else add map[curentItem] = idx
 * @param {*} array 
 * @param {*} target 
 */
function twoSumMethod2(array, target){
    const map = {};

    for (let i = 0; i < array.length; i++) {
        let com = target - array[i];
        if(map[com] !== undefined) return [i, map[com]]
        else map[array[i]] = i;
    }
    return -1
}
Enter fullscreen mode Exit fullscreen mode

Test Examples

const nums = [2,7,11,15], target = 9;
const nums = [3,3], target = 6

-

Anyway, if you have a better way of solving this, you can drop your solution in the comments. I'm no expert. Just learning aloud.

Don't forget to like, share and drop a comment. :)

Top comments (0)