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
- algodaily.com - The Two Pointer Technique
- www.geekforgeeks.org - Two Pointers Technique
- www.codingninjas.com - Two Pointer Approach
- jaigotec.com - [Algorithm(Ruby)] Explanation of the Two Pointer Technique
- qiita.com - Explanation of the Two Pointer Technique and Problems Using It
na.fuis.u-fukui.ac.jp - Two Pointer Technique- paiza.hatenablog.com - [Cumulative Sum, Two Pointer Technique] Algorithm Diagram for Beginners
- www.kumilog.net - Two Pointer Technique
- scrapbox.io - Two Pointer Technique