Algorithmsbasics

Two Pointers — Basics for Students

TT
Testlaa Team
May 14, 20261 min read

Two pointers means keeping two indices (left/right or i/j) and moving them based on comparisons. Many O(n) solutions come from never moving a pointer backward unnecessarily.

Try this in Python

def pair_sum_sorted(nums: list[int], target: int) -> tuple[int, int] | None:
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        s = nums[lo] + nums[hi]
        if s == target:
            return lo, hi
        if s < target:
            lo += 1
        else:
            hi -= 1
    return None


print(pair_sum_sorted([1, 2, 4, 6, 10], 8))

Key takeaways

  • Sorted array + pair sum is the hello-world pattern.
  • Pointers move toward each other.
  • Each step discards impossible half.

Tags:

Two pointersPythonStudents