Using Two-Pointer Technique to Optimize Algorithm Solutions

Using Two-Pointer Technique to Optimize Algorithm Solutions

There are three common ways to set the pointers: Start both pointers at the beginning of the iteration. Start both pointers at the end of the iteration. Start one pointer at the beginning, the other at the end, both moving toward each other and meeting in the middle.

When dealing with strings and arrays in the context of algorithm challenges, our first instinct usually revolves around built-in methods.

Let’s take a look at this seemingly easy problem:

/* Description:
Given a sorted (ascending) array of integers, 
write a function that returns a sorted (ascending) array 
which contains the square of each number.
*/
// Examples:
square([0, 1, 2, 3, 4, 5])
// => [0, 1, 4, 9, 16, 25])
square([-7, -3, 2, 3, 11])
// => [4, 9, 9, 49, 121]

Like many others, my immediate reaction was to make use of sort() method after mapping out (map()) the squared version of each integer, like so:

function square(arr) {
  arr = arr.map(num => num * num)
  return arr.sort((a, b) => a - b)
}

While my solution above achieves the desired result, its somewhat brute-force approach leads to a not-so-performant O(n log(n)) time complexity.

So how can we improve the runtime complexity?

This is where a popular and effective strategy, Two-Pointer Technique, comes into play.

When iterating over an array or string, we can set two pointers to search and/or compare two elements. There are three common ways to set the pointers:

  1. Start both pointers at the beginning of the iteration
  2. Start both pointers at the end of the iteration
  3. Start one pointer at the beginning, the other at the end, both moving toward each other and meeting in the middle.

Here’s how it works in our square() example:

Step 0:

Initiate an empty array that will store our results.

Step 1:

Create two pointers, i and j, where i keeps track of the negative integers, while j keeps track of the positives.

Step 2:

Iterate over the array. Keep moving j forward until the element of the array (arr[j]) is a positive integer.

Step 3:

Inside the iteration, compare the squared elements between index i and index j, push/append the smaller element to the resulting array.

Step 4:

After the iteration in Step 3, our resulting array will have a sorted set of integers. What remains is the element(s) at index i and index j.

We can subsequently push/append the remaining elements(s) to the resulting array.

coding web-development programming algorithms software-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Offshore Software Development - Best Practices

To make the most out of the benefits of offshore software development, you should understand the crucial factors that affect offshore development.

Software Developer vs Web Developer | Difference Web Developer & Software Developer

Software Developer vs Web Developer | Difference Web Developer & Software Developer | Software development and web development are normally used interchangeably. Although both include development, a software developer has different responsibilities from that of a web developer.

5 Core Criteria for Selecting Software Development Company - TopDevelopers.co

Check out these five criteria for the selection of your software vendor, and you will never regret having the wrong quality product made for you.

Developer Career Path: To Become a Team Lead or Stay a Developer?

For a developer, becoming a team leader can be a trap or open up opportunities for creating software. Two years ago, when I was a developer, ... by Oleg Sklyarov, Fullstack Developer at Skyeng company

7 Wastes In Lean Software Development [And How To Prevent Them]

In the 1930s, the Toyota Production System gave us lean manufacturing principles. Now, the IT, software and web development industry have also adopted these principles to improve their production processes. In actuality, the concepts and principles of Lean are used in more ways than just in manufacturing. Yet, in IT and software, there are still those who are pointing towards Agile development when they mention Lean and software development in the same context. While it is true that Agile and Lean principles share similar philosophies, there are key differences which set them apart. Diving deep inside Lean, I will discuss what lean talks about other than it’s key points.