Boss lesson · Unit 04
Search for the answer
Counting sort, then binary search with no list at all
What you practise
- Counting sort for small ranges
- Binary search over a yes/no answer space
Try a question from this lesson
Pick one
You have a million exam scores, each a whole number from 0 to 100. What is the fastest way to sort them?
Correct answer
Count how often each score occurs, then write them out
Why
With only 101 possible values, one pass tallies each score and a second writes the scores out in order: about n + 101 steps and not one comparison. O(n log n) is only the limit for sorts that compare items.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Counting sort
Counting sort never compares two items. It counts how often each value occurs, then walks the possible values in order and writes each one out that many times.
For n items with values from 0 to top, that is O(n + top) time, plus O(top) memory for the counters.
def counting_sort(nums, top):
counts = [0] * (top + 1)
for x in nums:
counts[x] += 1
out = []
for v in range(top + 1):
out += [v] * counts[v]
return outfunction countingSort(nums, top) {
const counts = Array(top + 1).fill(0);
for (const x of nums) counts[x]++;
const out = [];
for (let v = 0; v <= top; v++) {
for (let c = 0; c < counts[v]; c++) {
out.push(v);
}
}
return out;
}function countingSort(
nums: number[], top: number,
) {
const counts: number[] =
Array(top + 1).fill(0);
for (const x of nums) counts[x]++;
const out: number[] = [];
for (let v = 0; v <= top; v++) {
for (let c = 0; c < counts[v]; c++) {
out.push(v);
}
}
return out;
}Python note[0] * (top + 1) makes a list of zeros, and [v] * counts[v] makes that many copies of v.
JavaScript noteArray(top + 1).fill(0) makes an array of zeros: one counter for each possible value.
TypeScript noteconst counts: number[] = ... is annotated because Array(n).fill(0) alone is typed as any[], which would switch off checking.
Concept
A search with no list
A new kind of problem. There are piles of pages to read: 3, 6, 7 and 11 pages. Each hour you pick one pile and read up to speed pages from it. You have 8 hours. What is the smallest speed that finishes every pile in time?
There is no list to search. But the possible speeds 1, 2, 3, ... are in sorted order, and for any single speed you can work out whether it is fast enough.
Concept
Binary search on the answer
This is the lower-bound search, run on speeds instead of indexes.
Speed 1 is the slowest possible. The largest pile is always fast enough when there is an hour for every pile. The answer lies between them.
If mid finishes in time, the answer is mid or lower. If not, it is higher. The helper called in the if returns the hours needed at a given speed.
def min_speed(piles, hours):
lo, hi = 1, max(piles)
while lo < hi:
mid = (lo + hi) // 2
if hours_for(piles, mid) <= hours:
hi = mid
else:
lo = mid + 1
return lofunction minSpeed(piles, hours) {
let lo = 1, hi = Math.max(...piles);
while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
if (hoursFor(piles, mid) <= hours) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
}function minSpeed(
piles: number[], hours: number,
) {
let lo = 1, hi = Math.max(...piles);
while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
if (hoursFor(piles, mid) <= hours) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
}Python notemax(piles) returns the largest item of a list.
JavaScript noteMath.max(...piles) spreads the array into separate arguments, because Math.max takes numbers, not an array.
TypeScript noteWith no return type written, TypeScript infers number from return lo. Hover over the function in an editor to see it.
9 more exercises in the app
- 2× type the answer
- 4× multiple choice
- 1× true or false
- 2× fill the blanks
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.