Six problems about triples, quadruples and sorted sweeps. The move: fix all but two items, sort, and let each pointer step rule out a whole block of pairs.
You work on the back end of a banking app, a card-terminal service, a framing shop and a route planner. The six problems on this street ask about three or four items that must satisfy one rule, or about one item matched with a sorted list.
Checking every triple costs about n cubed steps. Sorting turns most of the work into a sweep. You fix the items you cannot sweep, and two pointers walk the rest.
| Problem | Fixed | The sweep | One step rules out |
|---|---|---|---|
| Evenly spaced check-in triples | the middle check-in | one pointer each side, moving outward | one check-in on the side with the smaller gap |
| Three entries that cancel out | the first entry | lo and hi on the sorted rest |
one entry, or a run of equal entries |
| Valid triangles from stick lengths | the longest segment | lo and hi below it |
every pair that ends at hi |
| Right-angle frames from rods | the longest rod | lo and hi on the squares below it |
one rod, or a run of equal rods |
| Best-paying route for each driver | the driver | one pointer over routes sorted by difficulty | nothing: the pointer never moves back |
| Four entries that hit the target | the first two entries | lo and hi on the rest |
one entry, or a run of repeated values |
The last column is where the speed comes from. A step that rules out a whole block is what turns n cubed into n squared.
Exercise · Predict the output: How many evenly spaced check-ins?. Each check-in is fixed as the middle one. One pointer moves left and one moves right, depending on which gap is smaller. What does the code print?
times = [0, 2, 4, 6, 7, 9]
count = 0
for j in range(1, len(times) - 1):
lo, hi = j - 1, j + 1
while lo >= 0 and hi < len(times):
left = times[j] - times[lo]
right = times[hi] - times[j]
if left == right:
count += 1
lo -= 1
hi += 1
elif right < left:
hi += 1
else:
lo -= 1
print(count)The move is a rule for choosing what to fix. Fix every item that the sweep cannot handle, and leave exactly two for the pointers. Then sort, so that moving one pointer changes the total in one known direction.
With the fixed items chosen and the data sorted, a pointer moves the total in one direction, so each step rules out a whole block of pairs untested.
Take the triangles. Sort the segments, fix the longest one at index k, and put lo at the shortest and hi immediately below k. If the two together beat the longest, then every segment from lo up to immediately below hi also does. That is hi - lo triangles in one step, and hi moves down.
If the two fall short, lo is too small for every length up to hi, so it moves up. On 1,000 random lengths, this sweep makes 498,501 steps. Testing every triple would make 166,167,000.
Exercise · Put it in order: Count triangles in one sweep. The segments are already sorted. Arrange the lines to count the triples that can form a triangle: fix the longest side, then sweep the shorter ones.
def count_triangles(segments):
count = 0
for k in range(len(segments) - 1, 1, -1):
lo, hi = 0, k - 1
while lo < hi:
if segments[lo] + segments[hi] > segments[k]:
count += hi - lo
hi -= 1
else:
lo += 1
return count
count += 1Fix the longest side. One match at the high pointer counts every segment from the low pointer up, so a step counts a block.
The Academy lesson 3-sum fixes the first entry and sweeps the rest. Opposite ends and Merging sorted sequences teach the sweeps themselves. This street changes four things.
The fixed item can be anywhere. In the spaced triples it is the middle, and the pointers move outward from it. In the triangles and the right-angle frames it is the longest, and the pointers move inside the part below it.
A step can count a block. The triangle sweep adds hi - lo for one match. When the total hits the target exactly, equal values at both ends need run lengths.
With entries 0, 0, 0, 0 and a target of zero, there are 4 triples: 3 with the first entry fixed and 1 with the second. When both ends hold equal values, the pairs inside the run number k * (k - 1) / 2.
Counting and listing differ. Three entries that cancel counts every triple of positions, so equal values multiply. Four entries that hit the target counts distinct value combinations, so repeated values are skipped. Read the statement for that one word.
The comparison is part of the problem. Three lengths of 1, 2 and 3 lie flat, so they make no triangle. Using >= instead of > counts one for them. A count of triples can also pass 32 bits: 3,000 equal sides give 4,495,501,000 triples.
One problem on the street has no sum at all. Each driver takes the best route their skill allows. Sort both lists, and one route pointer moves forward as skill rises, because a higher skill opens every route a lower skill opened.
Exercise · Break it: Counting one triple per match. This counts the triples of entries that add up to zero. It keeps the fixed entry and sweeps the rest, and adds one for each match. Find an input where it gives the wrong count.
def count_zero_triples(entries):
ordered = sorted(entries)
count = 0
for i in range(len(ordered) - 2):
lo, hi = i + 1, len(ordered) - 1
while lo < hi:
total = ordered[i] + ordered[lo] + ordered[hi]
if total < 0:
lo += 1
elif total > 0:
hi -= 1
else:
count += 1
lo += 1
hi -= 1
return countAdding one per match undercounts: on 2, 3, 4, 5, 6 it counts 4 triangles where the answer is 7. Add hi minus lo.
Solve them in this order. The first fixes the middle item. The next three fix the first or the longest, and the last two add a forward-only pointer and a second fixed item.
Before you code each problem, write three lines: what is fixed, what the two pointers sweep, and what one step rules out. If you cannot name the block a step rules out, the sweep is not yet right.
Give each problem about 20 minutes. Spend the first five on the three lines and on a hand walk of six or seven values, writing lo, hi and the total at every step.
Four edge cases come back on most rungs. The list may have fewer items than the problem needs, values may repeat, a comparison may need to be strict, and a count may pass two billion. Write one small test for each.
When a solution fails, compare the sweep with the block you claimed it rules out. Most wrong answers on this street come from a step that skips a pair that still counts.
hi - lo triangles at one match.0, 0, 0, 0 there are 4 triples, not 2. Distinct combinations skip repeats instead.Checkpoint · Sum families
Q1/5 In the evenly spaced check-in triples, which check-in is fixed while two pointers sweep?
Answer: B
The two gaps are measured from the middle check-in. The pointers move outward from it, and the one whose gap is too small reaches for a farther check-in.
Q2/5 The sorted segments are 2, 3, 4, 6, 7. The longest side is 7, and the pointers sit at 2 and 6. Since 2 + 6 beats 7, how many triangles does that one match count?
Answer: C
Every segment from the low pointer up to immediately below the high pointer, which are 2, 3 and 4, makes a triangle with 6 and 7. That is hi - lo = 3 triangles, then the high pointer moves down.
Q3/5 The segments are 1, 2 and 3. How many triangles do they form?
Answer: B
With equal sums the three lie flat on one line. The sweep must test > and not >=, otherwise it counts this flat triple.
Q4/5 The entries are 0, 0, 0, 0 and the triples must add up to zero. How many triples of positions are there?
Answer: C
Choosing 3 of the 4 equal entries gives 4 triples. A sweep that adds one per match and moves both pointers counts only 2.
Q5/5 Drivers are handled from the lowest skill to the highest, and routes are sorted by difficulty. Why can the route pointer only move forward?
Answer: B
The set of open routes only grows as skill rises. A forward-only pointer plus the best pay so far gives each driver's pay in one pass.
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.