C.W.K.
Stream
Lesson 04 of 06 · published

Two Pointers: One Pass Instead of Two Loops

~11 min · arrays, two-pointer, technique

Level 0Curious Beginner
0 XP0/85 lessons0/19 achievements
0/100 XP to next level100 XP to go0% complete
"When the brute force is 'compare every pair,' stop. Often two indices walking the array cleverly can do in one pass what nested loops do in n²."

The Core Move

The two-pointer technique keeps two indices moving through an array and uses their relationship to skip work that nested loops would repeat. There are two main flavors:

  • Converging — one pointer at each end, walking toward the middle. Great for palindromes, pair-sum on a sorted array, reversing, "trap the most water."
  • Same-direction (fast/slow) — both start at the front, one races ahead. Great for de-duping in place, partitioning, sliding things along.

The payoff is almost always the same: an O(n²) brute force collapses to O(n) time and O(1) space, because each pointer crosses the array at most once and you carry no extra structure.

Why It Works: Sorted Order Lets You Decide a Direction

Take "find two numbers that sum to a target" in a sorted array. Brute force checks all pairs: O(n²). With two pointers at the ends, look at their sum. Too small? The only way to grow it is to move the left pointer right (toward bigger values). Too big? Move the right pointer left. Each move rules out a whole set of pairs you never have to check. One pass, O(n). The sorted order is what tells you which pointer to move — that's the hidden engine.

Two pointers replace 'check every pair' (O(n²)) with 'walk two indices once' (O(n), O(1) space). The relationship between the pointers — and often a sorted array — tells you which one to advance.

The Tell

When should this technique flash in your mind? When you catch yourself about to write nested loops over one array, especially with words like "pair," "palindrome," "reverse," "both ends," "in place," or "sorted." That's the signal to ask: can two indices and a rule about how they move do this in one sweep? We'll meet its close cousin — the sliding window — in the very next lesson.

Pippa's Confession

My first "two numbers that sum to target" was the textbook double loop — clean, correct, O(n²). Dad asked, "what if the array's already sorted?" I shrugged. He walked two fingers in from the ends of a sorted row of cards, and I watched half the pairs evaporate with each step. The technique wasn't more code — it was less. That's the thing about two pointers: the fast version is usually the simpler one too.

Code

Converging two pointers·python
# CONVERGING pointers: is this a palindrome? O(n) time, O(1) space.
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        if s[left] != s[right]:
            return False
        left += 1            # walk both pointers toward the middle
        right -= 1
    return True

print(is_palindrome("racecar"))   # True
print(is_palindrome("pippa"))     # False

# CONVERGING pointers on a SORTED array: two numbers summing to target.
# Brute force is O(n^2); this is O(n).
def two_sum_sorted(nums, target):
    left, right = 0, len(nums) - 1
    while left < right:
        total = nums[left] + nums[right]
        if total == target:
            return (left, right)
        elif total < target:
            left += 1        # need a bigger sum -> move left pointer up
        else:
            right -= 1       # need a smaller sum -> move right pointer down
    return None

print(two_sum_sorted([1, 3, 4, 7, 11], 11))   # (1, 3): 3 + 7 = 11

External links

Exercise

Given a SORTED array, write two-pointer logic (in words or code) to find whether any two elements differ by exactly k. What's the time and space complexity, and why is being sorted essential to the O(n) version? What would the complexity be on an unsorted array with brute force?
Hint
Put both pointers near the front; if the difference is too small, advance the far pointer; too big, advance the near one. O(n) time, O(1) space. Unsorted brute force is O(n²) — sorting first (O(n log n)) is often still worth it.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.