Opposite Ends
Left starts at 0, right at the end, move inward on a condition. Two Sum II, Container With Most Water, Trapping Rain Water, Squares of Sorted Array, Valid Palindrome.
The simplest shape: a left pointer at the start, a right pointer at the end, moving inward based on whatever the problem is actually asking.
int twoSumSorted(int *nums, int n, int target, int *outL, int *outR) {
int l = 0, r = n - 1;
while (l < r) {
int sum = nums[l] + nums[r];
if (sum == target) { *outL = l; *outR = r; return 1; }
if (sum < target) l++; /* need a bigger sum — move left pointer up */
else r--; /* need a smaller sum — move right pointer down */
}
return 0;
}The trick that makes this work at all is that the array's sorted — moving l right can only increase the sum, moving r left can only decrease it, so every step is provably moving toward the target instead of just guessing.
Solved with this shape: Two Sum II, Container With Most Water, Trapping Rain Water, Squares of a Sorted Array, Valid Palindrome. Trapping Rain Water was the one where the logic clicked fast but the actual bugs were all stylistic — a good sign the pattern itself had sunk in.
Notes from readers
Comments — via GitHub