Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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
functiontwoSum(array,target){letlow=0;lethigh=array.length-1;while(low<high){constsum=array[low]+array[high];if(sum===target)return[low,high];if(sum>target)high--;elseif(sum<target)low++;}}
Enter fullscreen modeExit 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  */functiontwoSumMethod2(array,target){constmap={};for(leti=0;i<array.length;i++){letcom=target-array[i];if(map[com]!==undefined)return[i,map[com]]elsemap[array[i]]=i;}return-1}
Enter fullscreen modeExit 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Frontend Engineer
  • Location
    Lagos, Nigeria
  • Joined

More fromOlumideSamuel

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp