Topics/Strings/Two Pointers

Pattern

Two Pointers

Maintain two indices that move toward a goal — often from opposite ends or as a fast/slow pair — so you solve the problem in one linear pass.

StringsFundamentalsPattern

When to use it

Sorted arrays, palindrome checks, pair/triplet sums, in-place partitioning, and cycle detection in linked lists.

How it works

  1. Decide the starting positions (ends, or both at the start for fast/slow).
  2. Compare or accumulate state using both pointers.
  3. Advance the pointer that restores the invariant (e.g. sum too small → move left up).
  4. Stop when pointers cross or the slow pointer finishes the structure.

Solution

Reference implementation in C#, Python, Java, JavaScript, and C++.

Exact solutionTwo Pointers

Why interviewers care

Turns many O(n²) nested loops into O(n) after a sort, which interviewers expect you to spot quickly.

Drill Two Pointers with Strings problems — filter the bank and solve 2–3 Easy/Medium items while saying the invariant out loud.

Watch-outs

  • !Forgetting the array must be sorted for opposite-ends pair sum
  • !Off-by-one when L and R meet
  • !Mutating while both pointers share the same array
Loading visualization…

Practice this

Related Strings problems — open any one and apply Two Pointers.

Search bank →

More under Strings

← Back to Strings lesson