DEV Community

gbenga fagbola
gbenga fagbola

Posted on

Multiple Pointers

The idea of the multiple pointer pattern revolves solely around creating identifiers or pointers that correspond to an index or position, which moves towards a specific direction based on the condition set.

This pattern is quite efficient for solving problems with minimal space complexity.

Example:

Write a function that accepts a sorted array of integers. The Function in question should find the first pair of integers where the sum is 0, the expected output should return the pair of numbers whose value summed up to 0 and undefined if the pair does not exit.

function sumZero(arr) {

    let left = 0;
    let right = arr.length -1;

    while(left < right){
        let sum = arr[left] + arr[right];

        if(sum === 0){
            return [arr[left], arr[right]];
        } else if(sum < 0){
            left++
        } else if(sum > 0){
            right--
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

sumZero([-3, -2, -1, 0, 1, 2, 4])
returns [-2, 2]

sumZero([-4,2,1])
returns undefined

From the above block of code, we have a variable declared for pointers left and right. Such that the left pointer sweeps through the array from the first item in the list towards the ending of the list. While the right pointer starts from the end of the list and moves towards the beginning of the list. All this happens provided the left identifier wouldn't overlap with that of the right.

Top comments (0)