# How To Use The Two Pointer Technique

## When Do We Use It ?

1. Two pointers, each starting from the beginning and the end until they both meet.
2. One pointer moves at a slow pace, while the other pointer moves at twice the speed.

# Example

`var twoSum = function (nums, target) {    for (let i = 0; i < nums.length; i++) {         for (let j = i + 1; j < nums.length; i++) {             nums[i] + nums[j] === target             return [i, j]        }    }};`

## Solution With Hash

`var twoSum = function(nums, target) {    let storage = {};    for(let [index,num] of nums.entries()){        if(storage[num]!== undefined) return [storage [num], index];        storage[target- num ] = index    } };`

## Solution With Map

`var twoSum = function (nums, target) {     let numberIndex = new Map();     let result = [];     for (let i = 0; i < nums.length; i++) {      let num = nums[i];      let complement = target - num;      if (numberIndex.has(complement)) {       result[0] = numberIndex.get(complement)       result[1] = i;         return result;}      numberIndex.set(num, i)}}`

--

--

## More from Soner Mezgitci

Software Engineer | Ruby on Rails | JavaScript | HTML5 | CSS | PostgreSQL | React | Redux

Love podcasts or audiobooks? Learn on the go with our new app.

## Soner Mezgitci

31 Followers

Software Engineer | Ruby on Rails | JavaScript | HTML5 | CSS | PostgreSQL | React | Redux