HomeAll tracks · pricing · account
Python11 apps · Python, SQL & data
Start free Log in
Subscribe to unlock this lesson.
Subscribe to unlock this lesson.
Subscribe to unlock this lesson.
Subscribe to unlock this lesson.
Subscribe to unlock this lesson.
← Patterns 0 / 11
Loading Python in your browser… (first time ~10 MB)

Pattern 01Arrays & stringsEasy–Medium

Two Pointers

Walk in from both ends of a sorted list and throw away half the work with every step.

TimeO(n)SpaceO(1)Reach for itSorted array, pair sum, palindrome check, partitioning, removing duplicates

Start with the obvious way

A café’s menu is sorted from cheapest to priciest: `[1, 3, 4, 6, 8, 9, 11, 14]`. You have a £13 gift card and want to spend it exactly on two different items. The obvious way is to try every pair — the first item with each of the others, then the second with each of the rest, and so on.

⌘/Ctrl + Enter
Output
Run it to see the cost
The costEvery pair means n × (n − 1) / 2 checks: 28 for 8 items, 4,950 for 100, about half a million for 1,000. The list being sorted is information the nested loop simply ignores.