Eight interview problems about the two ends of a sequence. The move: put a pointer at each end and, at every step, drop the end that no remaining partner can improve.
You work on a ride app, a shop app and a streaming app. The eight problems on this street come from them. Each one pairs the two ends of a sequence, and each step of the answer asks which end to give up.
What a pair means changes from problem to problem. Here is each rule, and the end that is dropped at a step.
| Problem | The pair at the ends | The end you drop |
|---|---|---|
| Distinct team totals | lowest and highest score | both, after they are paired |
| Mirror the letters | the letters at the two ends | a symbol, or both after a swap |
| Trim matching ends | equal letters at the two ends | a whole run on each side |
| Palindrome after one deletion | a letter at each end | none, until a mismatch |
| Most bundles | two prices that add up to the target | the low, the high or both |
| Track selections | smallest and largest track | the low if it fits, else the high |
| Largest tank | two walls and the gap | the shorter wall |
| Rain trapped | two towers and their maxima | the lower tower |
Read the last column. A step never goes back. Each pointer moves in, so the pointers meet after at most n steps.
The street Pairs and complements finds a partner by a lookup. Here you find it by position, and the order of the sequence does the work.
Write one line before you code: which end is safe to drop, and why. The reason is the proof that the pointers never skip the answer.
At every step, no pair that uses an item outside the two pointers can beat the best found. So you may drop the end that no remaining partner can improve.
The water between towers shows it best. For a list of towers, the water above a tower is the lower of the tallest tower on each side, minus its own height. The left pointer knows the tallest tower to its left, and the right pointer knows the tallest to its right. The lower of the two towers decides which side is settled.
Exercise · Predict the output: How much water stays?. The code keeps the tallest tower seen from each end and moves the pointer at the lower tower. What does it print for these towers?
towers = [3, 0, 2, 0, 4]
lo = 0
hi = len(towers) - 1
left_max = 0
right_max = 0
water = 0
while lo < hi:
if towers[lo] < towers[hi]:
left_max = max(left_max, towers[lo])
water += left_max - towers[lo]
lo += 1
else:
right_max = max(right_max, towers[hi])
water += right_max - towers[hi]
hi -= 1
print(water)The same idea works for the largest tank. The tank is as high as the shorter wall and as wide as the gap. When the pointers move in, the width falls, so only a taller shorter-wall can help.
Exercise · Find the bug: Which wall do you give up?. This finds the largest tank between two walls, where a tank is as high as the shorter wall times the distance between them. It moves the two pointers in, one step at a time, but gives wrong answers. Which line is wrong?
def largest_tank(walls):
lo = 0
hi = len(walls) - 1
best = 0
while lo < hi:
best = max(best, min(walls[lo], walls[hi]) * (hi - lo))
if walls[lo] > walls[hi]:
lo += 1
else:
hi -= 1
return bestA tank is as high as the shorter wall and as wide as the gap, so drop the shorter wall and keep the taller.
The Academy lesson Opposite ends moves two pointers on a sorted list towards a sum. 3-sum fixes one item and runs the pair walk inside. Seen-set and complement finds a partner by lookup instead. This street changes four things.
Sort when positions do not matter. Team totals, bundles and track selections ask about values only, so sort first. The two ends are then the lowest and the highest.
Take the scores 1, 4, 2, 3, 8, 2. The sorted list is 1, 2, 2, 3, 4, 8, and the pairs from the ends total 9, 6 and 5.
Do not sort when positions matter. The tank and the towers depend on where a wall stands. The pointers start at the ends of the original list, and the rule of which end to drop must hold without any order.
A match can use two items. A bundle uses two items, so both pointers move in. On the prices 1, 1, 4 with a target of 5, the right answer is 1 bundle. If only the low pointer moves, the 4 is used twice and the code says 2.
A bundle uses two items, so move both pointers after a match, or one item is used twice.
One pair can stand for many. For the track selections, a pair of the smallest and largest track that fits counts every selection between them. The tracks in between are free to join or not. For the lengths 3, 5, 6, 7 and a slot of 9 the count is 4.
A power of two grows fast, so keep every power modulo 1,000,000,007. The power 2 to 99,999 reduces to 303,861,760.
A mismatch can branch once. For the almost palindrome, walk in while the letters agree. At the first mismatch try both choices, skipping the left letter or the right letter, and check the rest with a plain walk. The word cbbcc is a palindrome only if the right letter is skipped, so trying the left choice alone says no.
Exercise · Break it: The item used twice. This counts the most bundles of two different items whose prices add up to the target. Each item may be in one bundle only. It sorts the prices and moves two pointers. Find an input where it is wrong.
def most_bundles(prices, target):
ordered = sorted(prices)
lo = 0
hi = len(ordered) - 1
count = 0
while lo < hi:
total = ordered[lo] + ordered[hi]
if total == target:
count += 1
lo += 1
elif total < target:
lo += 1
else:
hi -= 1
return countSolve them in this order. The first two are plain walks. The next three drop an end for a reason you must state, and the last three need a count, a proof or a stored maximum.
Before you code each problem, write two lines: which end you drop at a step, and why dropping it can never lose the answer. If you cannot give the why, draw a small case and look for a counterexample.
Give each problem about 20 minutes. Spend the first three on the two lines. Then run your rule by hand on a list of six items, and write the two pointers under each step.
Three edge cases come back on most rungs. The list can have one item, the two ends can be equal, and every item can be the same. Write one small test for each before you run anything.
When a solution fails, check the drop rule first. Most wrong answers on this street have one of three causes. They are moving the wrong end, moving one pointer where a match uses two, or sorting a list whose positions matter.
Checkpoint · Pair finding
Q1/5 Two pointers start at the ends of a sequence. What must be true before you may move one pointer in?
Answer: B
The reason for the drop is the proof that no answer is skipped. Sorting is one way to get that reason, but the tank and towers need none.
Q2/5 In the largest tank problem, which wall do you give up at each step?
Answer: B
The tank is as high as the shorter wall and the gap only shrinks. Keeping the shorter wall can only give a smaller or equal tank. On 1, 8, 6, 2, 5, 4, 8, 3, 7 the best tank is 49.
Q3/5 Which of these problems should be solved without sorting the list first?
Answer: C
A wall's position gives the width of a tank, so sorting would destroy it. The other three ask about values only.
Q4/5 The prices are 1, 1, 4 and the target is 5. A code moves only the low pointer after a match. What does it return?
Answer: B
A bundle uses both items, so both pointers must move in. The right answer is 1 bundle.
Q5/5 For the lengths 3, 5, 6, 7 and a slot of 9, the pair 3 and 6 fits. How many selections with 3 as the shortest track does it count?
Answer: C
With 3 as the smallest track, the tracks 5 and 6 are free to join or not: {3}, {3, 5}, {3, 6} and {3, 5, 6}. That is 2 to the power of the gap, 2, which is 4.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.