Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Medium · Free

Explain the two-pointer technique with a sorted array example.

FresherFundamentalsData Structures & Algorithms
Model answer

Two pointers

On sorted array, move left/right based on sum vs target—O(n) after sort.

java
boolean pairSum(int[] a, int target) {
  int l = 0, r = a.length - 1;
  while (l < r) {
    int s = a[l] + a[r];
    if (s == target) return true;
    if (s < target) l++; else r--;
  }
  return false;
}
Also used for palindrome check, remove duplicates in-place.