Opposite Direction Pointers
What is this?
Picture two people walking toward each other from opposite ends of a hallway. At every step you look at the pair where they stand and decide which person should take the next step inward. Because one marker always advances and they never turn back, the gap between them closes steadily until they meet, letting you solve the problem in a single sweep instead of comparing every pair.
๐ก Fun fact: This is exactly how the classic "Container With Most Water" puzzle is solved. Always moving the shorter wall inward guarantees you never miss the best answer, even though you skip looking at most of the possible pairs.
๐ The 3 problems in this chapter are free. Sign in with Google or Microsoft to start solving.
Core idea: Put one pointer at each end of the array and walk them toward each other. At every step you ask "which end is spent โ which one can I retire knowing I've lost nothing?" โ advance that one. The window shrinks by one each step, so the whole scan is O(n) with O(1) space.
The shape of the pattern
Unlike a nested loop that re-examines pairs, opposite-direction pointers discard a candidate permanently on every move. The entire correctness argument lives in one sentence: why is it safe to advance this pointer instead of the other? Nail that discard rule and the code is four lines.
When to reach for it
- The array is sorted, or the answer depends on both ends (extremes).
- You're optimizing a quantity defined by a pair (max area, closest sum, a merged ordering).
- You can argue that moving one end can never improve the result, so it's safe to drop.
If the input isn't ordered but the strategy needs order (greedy from both ends), sort first โ that's the O(n log n) setup behind problems like Bag of Tokens.
The three problems in this chapter
Container With Most Water โ the discard rule, in its purest form
Two walls hold water up to the shorter of them, over the width between them. Start wide (L=0, R=n-1) and always move the shorter wall inward: the strong side is never the constraint, so retiring the weak side is the only move that can find something better.
โ area = min(h[L], h[R]) ร (R โ L); O(n) / O(1).
Squares of a Sorted Array โ the extremes hold the biggest values
After squaring a sorted (possibly negative) array, the largest squares sit at the two ends (most-negative vs most-positive). Compare the two ends, drop the bigger square into the result from the back, and step that end inward. A merge of two sorted runs without a sort.
โ O(n) / O(n) (output array).
Bag of Tokens โ sort, then play both ends
Sort the tokens. Buy a point with the cheapest token (left) when you can afford it; when stuck, sell a point by cashing in the priciest token (right) to refuel power. Track the high-water score.
โ O(n log n) to sort, then an O(n) two-pointer sweep.
The cross-cutting skill: the discard argument
| Problem | What "spent" means | Which pointer moves |
|---|---|---|
| Container With Most Water | the shorter wall caps the area | move the shorter wall |
| Squares of a Sorted Array | the larger magnitude is the next-biggest square | move the end with the bigger square |
| Bag of Tokens | cheapest buys a point; priciest refuels power | left to score, right to refuel |
Every opposite-end solution is "evaluate the pair, then move the spent end." If you can't say why the moved end is spent, you don't yet have a correct solution โ you have a guess.
๐ Draw it yourself
- The inward walk. Draw a row of bars,
Lat the left,Rat the right, arrows pointing inward, and write your discard rule above the picture. Re-draw it for each of the three problems โ the rule changes, the skeleton doesn't. - Fill-from-the-back. For Squares, draw the input with
L/Rand a separate result row being filled right to left. Seeing the result grow backward is the whole trick.
Snap photos and embed them with the /host-diagrams skill.
Complexity at a glance
| Problem | Time | Space |
|---|---|---|
| Container With Most Water | O(n) | O(1) |
| Squares of a Sorted Array | O(n) | O(n) output |
| Bag of Tokens | O(n log n) | O(1) extra |
Key takeaways
- Start at both ends, walk inward. The window shrinks by one each step โ O(n), O(1).
- The discard rule is everything. Decide which end is "spent" and prove moving it loses nothing.
- Sortedness powers the pattern โ and when a greedy needs order, sorting first (O(n log n)) is a legitimate setup, not a failure.
- Why interviewers like it: it exposes whether you can replace a nested loop with a justified linear sweep โ and whether you can argue correctness, not just code it.
Order: Container With Most Water โ Squares of a Sorted Array โ Bag of Tokens. The discard rule gets subtler each step.
Bag of Tokens
Core idea: Sort the tokens, then buy points with your cheapest token and refuel power by cashing in your most expensive token โ only when you're stuck โ tracking the best score you ever held.
Problem, rephrased
Think of yourself as a player at an arcade machine. You walk in with a fixed amount of energy (power) and 0 trophies (score). On the counter sits a pile of chips, each stamped with a number. You may play each chip exactly once, in whatever order you like, in one of two ways:
- Cash it in (face-up): if your energy is at least the chip's number, pay that much energy and win 1 trophy.
- Trade it back (face-down): if you hold at least 1 trophy, hand back 1 trophy and the machine refunds you the chip's number as energy.
You stop whenever you want. What is the most trophies you can be holding at once?
The whole game is a single trade: energy buys trophies, and a trophy buys energy. The art is deciding which chips to spend energy on and which chips to convert into energy.
tokens |
power |
Answer | Why |
|---|---|---|---|
[50] |
100 |
1 |
Cash in the 50 face-up: power 100 โ 50, score 1. |
[20, 60] |
40 |
1 |
Cash in 20 (power โ 20, score 1). Can't afford 60, and trading it back would only net 0 trophies. |
[15, 40, 20, 100] |
35 |
2 |
Shown in detail below. |
[10, 20, 30] |
100 |
3 |
Plenty of energy โ cash in all three. |
[] |
5 |
0 |
No chips, no trophies. |
Sign in to continue reading
The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.
Sign in to read the full lesson