Three problems where sorting first turns a question about every pair into one pass. The move: ask what a neighbour or a position tells you, and sort so that it does.
You work on the back end of an online store, a chat app and a video app. Three problems on this street come from them, and each one looks expensive. It seems to need a comparison of every item with every other item.
With 100,000 order times, that is 4,999,950,000 pairs. Sorting the same list takes about 1,660,964 comparisons. The sort is cheap, and it changes what the question needs.
| Problem | What it seems to compare | After sorting, the answer is |
|---|---|---|
| Smallest gap between two orders | every pair of order times on a clock | the smallest gap between two neighbours, and the gap round midnight |
| H index of a creator | the views of each video with the count of videos | the largest place i where the i-th largest views is at least i |
| Pairs processed out of order | every pair of messages | no single scan: the pairs are counted while merging |
Two of the three become one pass over the sorted list. The third shows where sorting alone stops, and the lesson comes back to it.
Here is the first idea in a few lines. Read the times, sort them, and look only at neighbours.
Exercise · Predict the output: The smallest neighbour gap. The code sorts five order times and keeps the smallest difference between two neighbours. What does it print?
times = [40, 7, 25, 12, 31]
times.sort()
best = times[-1] - times[0]
for i in range(1, len(times)):
best = min(best, times[i] - times[i - 1])
print(best)The move has two steps, and you take them before you write code.
First, ask what one neighbour or one position of the sorted list can tell you. Second, sort in the direction that makes it tell you that, and write down what the scan reads.
| The question | The sort | The scan reads | It tells you |
|---|---|---|---|
| The closest pair of values | ascending | the difference of two neighbours | the smallest gap in one pass |
| A rank rule, such as the h-index | descending | the value at place i | where the rule stops holding |
| How many pairs are out of order | by merging | a front of each half | the pairs that cross the halves |
In sorted order, a value between two others is never farther from one of them than the two are from each other. So the closest pair is a neighbour pair, and the count of items at least as large as an item is read from its position.
The h-index shows the second row. A creator has h-index h when at least h videos have h views or more.
Sort the views from largest to smallest. The video at place i, counting from 1, has i videos with at least its views. So it extends the answer when its views are at least i.
For the views 3, 0, 6, 1, 5 the sorted list is 6, 5, 3, 1, 0. Place 3 holds 3 views, which is at least 3. Place 4 holds 1, which is less than 4, so the answer is 3.
After sorting, the closest pair is a neighbour pair: compare each time with the next and keep the smallest gap.
Exercise · Find the bug: The h-index that never says zero. This scan sorts the views from largest to smallest and counts the videos that extend the h-index. It is right for most lists, but it gives a wrong answer for some. Which line is wrong?
def h_index(views):
views.sort(reverse=True)
count = 0
for v in views:
if v < count:
break
count += 1
return countThe Academy lesson The comparison model explains why a sort costs about n log n comparisons. Comparators in four languages shows how to sort in the direction you need, and Merge sort and inversions counts pairs while merging. This street does not teach those again. It changes three things about them.
The list can be a circle. Order times are seconds on a clock that repeats every 86,400 seconds. After sorting, the last time and the first time are neighbours too, and the gap between them is times[0] + 86400 - times[last]. For the times 86,399 and 1, the plain neighbour scan gives 86,398, and the right answer is 2.
On a clock the last time is also a neighbour of the first, so add the gap round midnight.
The scan reads a rank. The h-index never compares two videos. It compares each video's views with its place in the list, so the direction of the sort matters.
Sorting is not always enough. To count the pairs that arrive out of order, a sorted copy tells you nothing about how many pairs there were. The count has to be taken while merging. A list of 100,000 messages in exactly reverse order has 4,999,950,000 such pairs, which does not fit in a 32-bit int (the largest is 2,147,483,647).
Exercise · Put it in order: The smallest gap on a clock. Arrange the lines into a function that returns the smallest gap between two different order times on a clock of 86,400 seconds.
def smallest_gap(times):
times.sort()
best = 86400 + times[0] - times[-1]
for i in range(1, len(times)):
best = min(best, times[i] - times[i - 1])
return best
best = times[-1] - times[0]
best = 86400The count of pairs out of order is a trap for a quick idea: sort, and count how many values moved. The next block shows why that fails.
Exercise · Break it: Counting the messages that moved. This code counts the messages that arrive out of order by sorting a copy and counting the places that differ. Find an input where it gives the wrong count of out-of-order pairs.
def out_of_order(seqs):
ordered = sorted(seqs)
count = 0
for i in range(len(seqs)):
if seqs[i] != ordered[i]:
count += 1
return countSolve them in this order. The first is a plain neighbour scan with one twist, the second reads a rank, and the third needs the merge.
Before you code each problem, write two lines: what the scan reads, and which way the sort goes. If you cannot write the first line, the problem is the last rung: the answer is not in the sorted list.
Give each problem about 20 minutes. Spend the first three on the two lines, and say them out loud as you would to an interviewer. Then list the edge cases before you run anything.
Three edge cases come back on every rung. A list can hold one item or equal items, a wrap can hide the closest pair, and a count of pairs can pass two billion. Write one small test for each.
When a solution fails, look at the two lines first. Most wrong answers on this street come from a scan that reads the wrong thing, or from a sort in the wrong direction.
Checkpoint · Sort then scan
Q1/5 Why does the closest pair of values have to be a pair of neighbours in sorted order?
Answer: B
If a < b < c, then c - a is at least b - a. A pair with another value between them is never the closest, so only neighbours need a check.
Q2/5 The order times are 86,399 and 1 on a clock of 86,400 seconds. The sorted scan reads only neighbour differences. What does it return?
Answer: B
The scan sees one neighbour pair, 1 and 86,399, which are 86,398 apart. The gap round midnight, 1 + 86,400 - 86,399 = 2, is a neighbour pair on the clock.
Q3/5 The views are 6, 5, 3, 1, 0 in sorted order. What is the h-index?
Answer: C
Place 3 holds 3 views, which is at least 3. Place 4 holds 1 view, which is less than 4. So three videos have at least 3 views each.
Q4/5 Why can sorting a copy and counting the places that changed not give the number of pairs out of order?
Answer: C
In 2, 3, 1 all three places differ from the sorted list, but only two pairs are out of order. The pairs must be counted while merging.
Q5/5 A list of 100,000 messages arrives in exactly reverse order. How many pairs are out of order, and what holds the count?
Answer: C
Every pair is out of order: 100,000 × 99,999 / 2 = 4,999,950,000. A 32-bit int holds at most 2,147,483,647.
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.