Two Pointers
GOALClose in from both ends of a sorted array to find a pair.
"Are there two numbers adding to exactly S?" A double loop makes that O(n²). But if the array is sorted you can start at both ends: too big, move the right pointer left; too small, move the left pointer right. One pass and you are done.
ON THIS PAGE
//THE EXAMPLE
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {1, 3, 4, 7, 11};
int target = 10;
int lo = 0, hi = (int)v.size() - 1;
bool found = false;
while (lo < hi) {
int sum = v[lo] + v[hi];
if (sum == target) {
cout << v[lo] << " " << v[hi] << endl;
found = true;
break;
}
if (sum < target) lo++;
else hi--;
}
if (!found) cout << "none" << endl;
return 0;
}3 7
//LINE BY LINE
Watch it run
A sorted array. lo starts at the left end, hi at the right.
The other shapes this takes
Closing in from both ends is only one shape. Two pointers can also move the same way together, making a sliding window.
| Shape | Used for |
|---|---|
| Хоёр захаас дунд руу / Both ends inwards | Нийлбэр нь S болох хос / a pair adding to S |
| Хоёулаа урагш / Both moving forward | Хамгийн урт хэсэг / longest run with a property |
| Нэг нь хурдан, нэг нь удаан / One fast, one slow | Дундажийг олох, мөчлөг илрүүлэх / finding the middle, detecting a cycle |
The gain is always the same: each pointer crosses the array ONCE. That is what turns O(n²) into O(n).
When it needs sorted data
The closing-in shape leans on the data being SORTED: "the sum is too big" only tells you to move the right pointer if the values are in order.
| Shape | Needs sorting? |
|---|---|
| Хоёр захаас дунд руу / Both ends inwards | Тийм / yes |
| Хөдлөх цонх / Sliding window | Үгүй / no |
| Хурдан ба удаан / Fast and slow | Үгүй / no |
Sorting costs O(n log n), slower than the O(n) walk itself. It is still far faster than the O(n²) you replaced.