Two Pointers — Opposite Ends

Place L at index 0 and R at index n−1. Compare and move one pointer inward each step based on the result — they converge until they meet.

Sorted Array String Time O(n) Space O(1)
📋 When to Use
  • Array is sorted (or sortable) and you need a pair
  • Find two elements that sum to a target
  • Check if a string is a palindrome
  • Maximize/minimize a value using elements from both ends
💡 Key insight: If sum < target → left element is too small, move L right. If sum > target → right element is too large, move R left. Sorted order guarantees correctness.
⚡ Complexity
Time
O(n)
Space
O(1)

Each pointer moves at most n steps total. L only moves right, R only moves left — they can never revisit an element. No extra memory needed.

⚠️ Brute force is O(n²). Two pointers reduces it to O(n).

Live Animation · Two Pointers Opposite Ends · LC #167
Problem Given a sorted array nums and an integer target, find two numbers that add up to the target. Return their 1-indexed positions. Use two pointers starting at opposite ends — move L right if sum is too small, move R left if sum is too large.
Input: nums = [1, 4, 5, 6, 7, 8], target = 11  ·  Answer: [2, 4] (nums[1]+nums[3] = 4+7 = 11)
Step 1 / —
🔍 Compare
→ Move L right (sum too small)
← Move R left (sum too large)
✅ Found!
🏁 Done
L Pointer
index =
+
vs target = 11
R Pointer
index =
Click ▶ Play or Next ▶ to begin.
int left = 0, right = nums.length - 1;
Complete Java TemplateJAVA
// Two Pointers — Opposite Ends
int left = 0, right = nums.length - 1;

while (left < right) {
    int val = f(nums[left], nums[right]);  // e.g. sum, product, area

    if (val == target) {
        // found — record answer or return
        break;
    } else if (val < target) {
        left++;    // need larger → move left inward
    } else {
        right--;   // need smaller → move right inward
    }
}
🎯 Practice Problems