Learn hub

Two Pointers — Two Indices, One Rule

Move left/right based on a condition instead of checking all pairs.

Suno.Heightarraydiyahai.Dowallschoosekaro.Panikitnabharsakteho?Area=minheight×width.

Listen. You get a height array. Pick two walls. How much water fits? Area = min height × width.

0:00 / 1:03

When to use this

  • Sorted pair/triplet
  • Palindrome ends
  • In-place partition

C++ template

int L = 0, R = n - 1;
while (L < R) {
    int sum = a[L] + a[R];
    if (sum == target) { L++; R--; }
    else if (sum < target) L++;
    else R--;
}

Dry run

Container water → move shorter wall → best 49.

Pitfalls

  • Unsorted when sum needs sort
  • L/R never move
  • Wrong pattern choice

Say this in the interview

Pointers move at most n steps → O(n) after sort.

Problems in this topic (7)

Each opens teach-first (animated when available), then the code panel.