The idea
Keep two indexes, left at the start and right at the end. Look at both, decide which one to move, and repeat until they meet. Every step moves one of them, so there are at most n steps.
Think of it like this: Two friends searching a long shelf for two books that together cost exactly ₹500 – one starts at the cheap end, the other at the expensive end, and they walk toward each other.
Example: closest pair to a target
The array is sorted. If the sum is too small, the only way to make it bigger is to move left right. If it's too big, move right left:
public class Main {
public static void main(String[] args) {
int[] weights = {3, 8, 11, 15, 21, 30}; // sorted
int target = 25;
int left = 0, right = weights.length - 1;
int bestSum = weights[left] + weights[right];
while (left < right) {
int sum = weights[left] + weights[right];
System.out.println("try " + weights[left] + " + " + weights[right] + " = " + sum);
if (Math.abs(sum - target) < Math.abs(bestSum - target)) bestSum = sum;
if (sum == target) break;
if (sum < target) left++;
else right--;
}
System.out.println("closest sum: " + bestSum);
}
}Output
try 3 + 30 = 33 try 3 + 21 = 24 try 8 + 21 = 29 try 8 + 15 = 23 try 11 + 15 = 26 closest sum: 24
Remember: Two pointers needs a reason to move one side – usually because the array is sorted.