Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Data Structures and Algorithms
  • What a Data Structure Is, and How Memory Works
  • Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
  • Linked Lists: A Chain of Clues, Built in Python
  • Stacks: Last In, First Out, With the Undo Button
  • Queues: First In, First Out, With a Ring of Cells
  • Hash Tables: The Name Tells You Where to Look
  • Binary Search Trees: Smaller Left, Bigger Right, Half Gone at Every Look
  • Tree Traversals: In-Order, Pre-Order and Post-Order as a Tour of the House
  • Heaps and Priority Queues: Most Urgent First, Without Searching the Room
  • Graphs and Breadth-First Search (BFS): Fewest Hops, Level by Level
  • Big-O: Reading Cost From Code, With Handshakes and a Guest Book
  • Recursion: Russian Dolls, the Base Case and the Call Stack
  • Linear vs Binary Search: Page by Page, or Open in the Middle
  • Insertion Sort: Take the Next Card and Slide It Left Until It Fits
  • Merge Sort: Split the Pile, Then Merge Two Sorted Piles
  • Quick Sort: Line Up Around One Friend, Then Repeat on Each Side
  • Depth-First Search (DFS): Go Deep, Back Up, Mark Where You've Been
  • The Two Pointers Technique: Find a Pair in One Pass Instead of Every Pair
  • The Sliding Window Technique: One In, One Out
  • Greedy Algorithms: The Best-Looking Choice, Right Now
  • Dynamic Programming: Work It Out Once, Write It Down, Read It Back
  1. Blog
  2. /
  3. Data Structures and Algorithms
  4. /
  5. Algorithms

The Two Pointers Technique: Find a Pair in One Pass Instead of Every Pair

Emma wants two gifts that add up to her 36 dollar card. Trying every pair takes 20 checks; two pointers, walking in from both ends of the sorted prices, takes 6. Why it's safe, how it scales to 10,000 gifts, and how an unsorted list breaks it.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Algorithms

What you will learn

  • Explain how two pointers walk in from both ends of a sorted list
  • Explain why a dropped item can never be part of the answer
  • Compare every-pair O(n squared) with two pointers O(n) on real check counts
  • Recognise why two pointers gives a wrong answer on an unsorted list

Before you start

  • Python lists and indexes
  • Big-O notation

Emma has a gift card worth 36 dollars. The shop has eight gifts, sorted from the cheapest to the dearest: 4, 5, 11, 14, 18, 22, 28 and 35. She wants two gifts that add up to exactly 36. The plain way is to try every pair, and eight gifts make 28 pairs. The answer is 14 plus 22, and two pointers finds it with far fewer checks.

Two friends walk towards each other

Imagine a shelf of gifts, cheapest to dearest. Jack stands at the cheap end and Kate at the dear end, and they want two gifts that make 14 dollars. 1 plus 12 is 13: too little, so Jack steps right, to a dearer gift. 5 plus 12 is 17: too much, so Kate steps left, to a cheaper gift. 5 plus 9 is 14, exactly right.

They never walk back. Jack's side only gets dearer, and Kate's side only gets cheaper. Each step drops one gift for good. That's the two pointers idea.

Why a gift can be dropped

Take Emma's list. Kate starts on 35. Pair 35 with the cheapest gift, 4, and you get 39, already too much. Every other partner is dearer, so every pair with 35 is over 36. Drop it.

Now Jack is on 4, and the dearest gift left is 28. 4 plus 28 is 32, too little. Every other partner is cheaper, so 4 can never reach 36. Drop it.

If the best partner isn't good enough, no partner is. So a dropped gift could never have been part of the answer, and one pass is enough. But this only holds because the list is sorted.

Sorted prices 4, 5, 11, 14, 18, 22, 28, 35 with left starting at 4 and right at 35. They walk in: 4 and 35 is too much, right moves; 4 and 28 too little, left moves; and so on until 14 plus 22 equals 36 after six checks. 4 5 11 14 18 22 28 35 left starts right starts too little: left + 1 too much: right - 1 14 + 22 = 36 after 6 checks
Every check drops one gift from one end, so the pointers meet in one pass.

The plain way: every pair

def find(prices, card):
    checks = 0
    for i in range(len(prices)):
        for j in range(i + 1, len(prices)):
            checks += 1
            if prices[i] + prices[j] == card:
                return f"{prices[i]} + {prices[j]} ({checks:,} checks)"
    return f"no pair ({checks:,} checks)"

The outer loop picks the first gift, the inner loop pairs it with every gift after it. A loop inside a loop.

The new way: two pointers

def find(prices, card):
    left = 0                    # Jack: the cheapest gift
    right = len(prices) - 1     # Kate: the dearest gift
    checks = 0
    while left < right:
        checks += 1
        total = prices[left] + prices[right]
        if total == card:
            return f"{prices[left]} + {prices[right]} ({checks:,} checks)"
        if total > card:
            right -= 1      # too much: Kate steps left
        else:
            left += 1       # too little: Jack steps right
    return f"no pair ({checks:,} checks)"

One loop. Every check moves one pointer one step, so eight gifts need at most seven checks.

import every_pair
import two_pointers

prices = [4, 5, 11, 14, 18, 22, 28, 35]   # sorted
card = 36                                 # Emma's gift card

slow = every_pair.find(prices, card)
fast = two_pointers.find(prices, card)
print("Every pair:   " + slow)
print("Two pointers: " + fast)
Every pair:   14 + 22 (20 checks)
Two pointers: 14 + 22 (6 checks)

Step by step

Checkleft + rightSumMove
14 + 3539, too muchright - 1 (35 dropped)
24 + 2832, too littleleft + 1 (4 dropped)
35 + 2833, too littleleft + 1
411 + 2839, too muchright - 1
511 + 2233, too littleleft + 1
614 + 2236found

Ten thousand gifts

import every_pair
import two_pointers

for n in (100, 1_000, 10_000):
    prices = [0] * n
    for i in range(n):
        prices[i] = i + 1      # 1, 2, 3 ... n: sorted
    card = n + (n - 1)         # only the two dearest fit
    print(f"{n:>6,} gifts  every pair:   {every_pair.find(prices, card)}")
    print(f"{n:>6,} gifts  two pointers: {two_pointers.find(prices, card)}")
   100 gifts  every pair:   99 + 100 (4,950 checks)
   100 gifts  two pointers: 99 + 100 (99 checks)
 1,000 gifts  every pair:   999 + 1000 (499,500 checks)
 1,000 gifts  two pointers: 999 + 1000 (999 checks)
10,000 gifts  every pair:   9999 + 10000 (49,995,000 checks)
10,000 gifts  two pointers: 9999 + 10000 (9,999 checks)

Ten times more gifts means about a hundred times more checks for every pair, but only ten times more for two pointers.

Breaking it: a mixed-up list

import every_pair
import two_pointers

prices = [4, 11, 5, 28, 14, 22, 18, 35]   # NOT sorted
card = 36

slow = every_pair.find(prices, card)
fast = two_pointers.find(prices, card)
print("Every pair:   " + slow)
print("Two pointers: " + fast)
Every pair:   14 + 22 (23 checks)
Two pointers: no pair (7 checks)

Two pointers trusts the order. It assumes everything Jack passed was cheaper and everything Kate passed was dearer. Here that isn't true, so at one point Kate steps left and drops 22, half of the answer, and the pointers meet with "no pair". That's wrong. Every pair doesn't care about order and still finds 14 plus 22. Two pointers works only on a sorted list. Sort first, for example with sorted(), but sorting costs more than the walk itself, so the technique pays off best on a list that's already in order.

What it costs

ApproachChecks for 8 giftsCostNeeds sorted list?
Every pairup to 28O(n²)no
Two pointersat most 7O(n)yes

Where you meet it

  • Two items that fit a budget on a sorted price list, like Emma's.
  • Checking a word that reads the same backwards, like "level": compare first and last, then walk in.
  • Reversing a word: swap the two ends, then walk in until they meet.
  • Merging two sorted piles: a marker at the front of each, always take the smaller card.

Different places, one idea: two markers that only ever move one way. A close relative is the sliding window, where both markers move the same way.

Try it yourself

Change the card to 33 and count how many checks two pointers needs.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Data Structures and Algorithms · 18 of 21

Previous
Depth-First Search (DFS): Go Deep, Back Up, Mark Where You've Been
Next post
The Sliding Window Technique: One In, One Out

Related courses on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Data Structures and Algorithms Concepts: No Coding Needed

How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)

Related posts

Big-O: Reading Cost From Code, With Handshakes and a Guest Book

Big-O asks one question: how do the steps grow when the list grows? Check a school trip sheet for duplicates two ways, handshakes and a guest book, count every step in Python, then grow the list to ten thousand ids and watch 10,000 steps turn into almost 50 million.

Recursion: Russian Dolls, the Base Case and the Call Stack

Recursion means doing the same job on a smaller piece of the problem, and stopping at a base case. Count Emma's Russian dolls with a Python function that calls itself, watch each call wait on the call stack so the answers come back in reverse, then take the base case out and meet RecursionError.

Linear vs Binary Search: Page by Page, or Open in the Middle

Is kite a real word? Page by page takes 11 checks; opening in the middle takes 4. Trace binary search step by step, see a million words answered in 20 checks, and watch it give the wrong answer on an unsorted list.

Insertion Sort: Take the Next Card and Slide It Left Until It Fits

Emma's hand 7, 3, 9, 2, 5 sorted one card at a time in 6 shifts. Trace each card, see why a backwards hand costs the most, why 5,000 shuffled cards need over 6 million shifts, and why a sorted hand needs zero.

On this page

  • Two friends walk towards each other
  • Why a gift can be dropped
  • The plain way: every pair
  • The new way: two pointers
  • Step by step
  • Ten thousand gifts
  • Breaking it: a mixed-up list
  • What it costs
  • Where you meet it
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related courses on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Data Structures and Algorithms Concepts: No Coding Needed

How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.