About the Two Pointer Technique

Master two-pointer technique for efficient array pair searching with O(N log N) complexity using sorting and index manipulation.

Read in: ja
About the Two Pointer Technique

Overview

This post summarizes the Two Pointer Technique.

In English, it is called the Two Pointer Approach or Two Pointer Technique.

What is the Two Pointer Technique?

It is an algorithm that maintains the indices of the right and left ends of a dataset (such as a sequence or string) and moves the indices based on certain conditions to search for data that meets those conditions.

It is useful when you want to search for data that meets specific conditions within a range.

Example Problem

Write a function to find how many pairs of numbers in array n are less than a specified number m.

For example, if n = [1, 3, -1, 2] and m = 4, there are four pairs that meet the criteria: (1, -1), (1, 2), (3, -1), and (-1, 2), so the function should return 4.

The code for a straightforward implementation of the function is as follows:

func findPairs(n []int, m int) int {
    rslt := 0
    for i := 0; i < len(n); i++ {
        for j := i+1; j < len(n); j++ {
            if (n[i] + n[j]) < m {
                rslt++
            }
        }
    }
    return rslt
}

This results in a time complexity of O(N^2), so we use the Two Pointer Technique to reduce it to O(N log N).

func findPairs(n []int, m int) int {
    sort.Ints(n)
    cnt, l, r := 0, 0, len(n)-1
    for l < r {
        if n[l] + n[r] < m {
            cnt += r-l
            l++
            continue
        }
        r--
    }
    return cnt
}

By repeating until the left and right indices overlap, you can explore all pairs that meet the conditions.

Sorting is done to make it easier to efficiently find pairs.

Although r-l might seem counterintuitive, since the code is for finding pairs, it focuses on counting pairs by indices rather than the values themselves in the array, resulting in this kind of code.

References

Tags: Two-Pointer Technique Two-Pointer Approach
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles