Logic Building Bootcamp · Lesson 2 of 5

Pattern 2 — Two Pointers

Sometimes you don't need two loops — you need two fingers. This pattern is exactly that, and it's one of the tidiest tricks you'll learn.

By Shahriyar · Updated

The idea, in one line

Put one marker at each end of a list and walk them toward each other, doing one pass instead of a loop inside a loop. That's the two pointers pattern.

How to spot it

The big signal is a sorted list, or a string you compare from the front and the back at the same time. The task usually asks for one of these:

The move, step by step

  1. Put left at the first index and right at the last.
  2. Add the two values and compare to the target.
  3. Total too small? Move left up one to gain value.
  4. Total too big? Move right down one to lose value.
  5. Equal? You found your pair. Keep going while left is below right.

See it work

▸ try it
# Two response times that add up to a target budget (sorted input)
def has_pair(nums, target):
    left, right = 0, len(nums) - 1
    while left < right:
        total = nums[left] + nums[right]
        if total == target:
            return (nums[left], nums[right])
        if total < target:
            left += 1        # need more -> move left up
        else:
            right -= 1       # too much -> move right down
    return None

print(has_pair([1, 2, 4, 5, 9], 9))   # (4, 5)

Read it top to bottom: start at both ends, nudge whichever end you need, and stop the moment the two markers meet. A palindrome check is the very same shape — compare the two ends, step inward, and fail the instant they differ.

▸ try it
# Palindrome check: compare the ends, step inward
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        if s[left] != s[right]:
            return False
        left, right = left + 1, right - 1
    return True

print(is_palindrome("abccba"))   # True

Advanced — why it's fast, and why sorting matters

Because the list is sorted, it has a direction: moving a pointer doesn't just skip one item, it rules out a whole range you'll never need to check again. That's what turns a slow double loop into a single pass.

Grounded in the GeeksforGeeks 'Two Pointers Technique' tutorial

All lessons in Logic Building Bootcamp

  1. Pattern 1 — Counting how often things appear
  2. Pattern 2 — Two Pointers
  3. Pattern 3 — Sliding Window
  4. Pattern 4 — Index Math & Matrix Walks
  5. OOP Essentials — Classes, Inheritance, Magic Methods, Decorators