1624900980

# Intro to Algorithms: Two Pointers Technique

In my last post, I covered the ins and outs of the Binary Search algorithm. The binary search method assumes that the collection you are browsing has already been sorted, and the two pointers technique is no different. However, whereas binary search locates a single element within a collection, the two pointers technique is used to locate two elements within an array that together meet a condition. Let’s take a look at how it works.

## Charging Ahead: A Naive Solution

Let us turn to a brute force, naive solution to a problem where the two pointers technique might be better suited.

Given an array of integers (already sorted in ascending order) find and return the indices of the two elements that, when added together, are equal to the provided target value.

Or given an `array` and a `target`, write an algorithm that solves for `array[i] + array[j] === target`.

How might we devise a brute force approach to this problem? Well, the first step would be to iterate through each element in the array. Then we would have to check each selected element with the remaining elements in our collection, testing if their sum matches the target value. Sounds like a job for some nested loops.

This solution does technically work, but it’s woefully inefficient. You have to iterate through the entire array for each element in the array until the solution is found! This might not sound terrible if the array is three or four elements long. But imagine doing this with an array that’s one million elements long. You’d have to count to one million (technically 999,999) before you’d even progress to the second element! Think about how long that would take if our solution was to be found in the last two elements in the array.

This method has a Big O notation of O(n²), meaning that as the size of our array grows, the time it takes to find our answer grows exponentially. Not ideal at all. How might we devise a better solution?

#javascript #web-development #programming #coding #algorithms #intro to algorithms