JavaScript Program for Two Pointers Technique



In this article we are given a sorted array, our task is to find if there exists any pair of elements such that their sum is equal to a given number. Users must be familiar with array, loop and nested loops, and if/else statement.

Two Pointers Technique

Two pointers technique is a commonly used algorithmic approach to solve various problems that require linear time complexity. This technique is used to find a solution for problems that involve searching, sorting, or manipulating arrays, strings, or linked lists. In this article, we are going to solve the pair sum problem using brute force and two pointers technique.

Two Pointers Technique Example - Pair Sum Problem

One of the best examples of two pointers technique is to solve pair sum problemThe pair sum problem is used to find a pair of numbers in the sorted array whose sum is equal to the target. Where, sorted array and target is given.

Here is an example of pair sum problem with input and output scenarios:

Input:
array = [1, 3, 5, 7, 9], X = 12
Left = 1, Right = 9, sum = 10
since sum < x, left++ => left = 3

Now, Left = 3, Right = 9, sum = 12
since sum = x, 
return index of Left(3) & Right(9) i.e 1 and 4 

Output:
Pair found at indices 1 and 4

Approaches for Solving Pair Sum Problem

Here is a list of approaches which we will be discussing in this article with stepwise explanation and complete example codes.

Using Brute Force Approach

In this approach to find the pair with given sum, we will use brute force approach where we iterate over each elements of the array to find the pair with given sum.

  • We have declared an array and a variable initially. We have defined a function findSumPair() that accepts the array and target sum value as its argument.
  • In the function, first we get the length of the array using length property.
  • Then we have used two for loop, where first for loop selects an element from the array and second for loop iterates over the loop making pairs with the selected element using first for loop.
  • If the sum of the element in pair is equal to required sum, then function returns the indices of elements in pair in web console using console.log().
  • If the pair is not found then message is displayed pair not found.

Example

Here is a complete example code implementing above mentioned steps using brute force approach.

const array = [1, 3, 5, 7, 9];
const X = 10;
console.log(`Array: ${array}`);
console.log(`Target sum: ${X}`);

function findSumPair(array, X) {
    const n = array.length;
    for (let i = 0; i < n - 1; i++) {
        for (let j = i + 1; j < n; j++) {
            if (array[i] + array[j] === X) {
                console.log(`Pair found at indices ${i} and ${j}`);
                return [i, j];
            }
        }
    }
    console.log("Pair not found");
    return null;
}

findSumPair(array, X);  

Using Two Pointers Technique

We have used two pointers technique to find the pairs in array with given sum.The two pointers is an efficient technique to solve problems of sorted arrays. We maintain two pointers (such as left and right in this example) at different positions and moving them according to requirement. It helps in getting better time complexity than using nested loops.

  • We have declared an array and a variable initially. We have defined a function findSumPair() that accepts the array and target sum value as its argument.
  • Then we have defined two pointers, left and right where left pointer represents first element of the array and right pointer points to last element of the array.
  • Then we find sum using left and right indices. If the sum is equal to the target, return the indices left and right.
  • If the sum is less than the target, increment left and the sum is greater than the target, decrement right. This loop continues till left pointer is less than right pointer using while loop.
  • If no such pair exists, return null.

Example

Here is a complete example code implementing above mentioned steps using two pointers technique.

const array = [1, 3, 5, 7, 9], X = 12;
console.log(`Array: ${array}`);
console.log(`Target sum: ${X}`);

function findSumPair(array, X) {
    let left = 0;
    let right = array.length - 1;
    while (left < right) {
        const sum = array[left] + array[right];
        if (sum === X) {
            console.log(`Pair found at indices ${left} and ${right}`);
            return [left, right];
        } else if (sum < X) {
            left++;
        } else {
            right--;
        }
    }
    console.log('Pair not found');
    return null;
}

findSumPair(array, X);

Complexity Comparison

Here is a comparison of time and space complexity of all the above approaches.

Approach Time Complexity Space Complexity
Brute Force O(n^2) O(1)
Two Pointers O(n) O(1)

In this article we have discussed a JavaScript program for two pointers technique, where we first discussed the brute force approach to solve the problem and then used two pointers approach to solve the problem. The two pointers technique is efficient than brute force as mentioned in the time complexity table.

Practice and learn from a wide range of JavaScript examples, including event handling, form validation, and advanced techniques. Interactive code snippets for hands-on learning.

Updated on: 2025-06-06T12:33:05+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements