BeginnerCoder

Lesson 14 — Two pointers

Two pointers on a sorted list

Find two numbers in a sorted list that add up to a target — without a dict this time. Put pointer i at the start and j at the end. If a[i] + a[j] is too small, move i right (bigger numbers); if too big, move j left (smaller numbers); if equal, done.

# [1, 3, 4, 6, 9], target 10: 1+9=10 -> found at once

Every step throws away one candidate, so it is O(n) and needs no extra memory.

Why it matters: two pointers solves many sorted-array problems (pairs, merging, removing duplicates) in a single pass.

Want it another way?
Task

Fill in the two moves. Expected: (4, 6), then (1, 9), then None.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.