Algorithmstechnique

Two Pointer Technique — Dual Traversal

TT
Testlaa Team
May 14, 20261 min read

The technique is: define invariants (what lo and hi mean), prove each move preserves them, and stop when pointers cross or meet.

Try this in Python

def reverse_words_inplace(s: list[str]) -> None:
    """Toy: reverse a char array using two ends (idea only)."""
    lo, hi = 0, len(s) - 1
    while lo < hi:
        s[lo], s[hi] = s[hi], s[lo]
        lo += 1
        hi -= 1


a = list("hello")
reverse_words_inplace(a)
print("".join(a))

Key takeaways

  • Same two-index idea works on one sequence from both ends.
  • Always state what each pointer represents.
  • Draw the array before coding.

Tags:

Two pointersPythonStudents