How To Use The Two Pointer Technique

What Is 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 } };

Explanation

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)}}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Soner Mezgitci

Soner Mezgitci

31 Followers

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