Suppose a job has 1,000 tasks, each with some number of records. A worker handles one task at a time, a batch of size records per minute, and a part-full batch still takes a whole minute. The job must finish in 2,000 minutes, and the direct way to find the smallest size that fits tries 1, 2, 3 and so on. Save it as opening-slow.ts:
// Opening problem: the smallest batch size that finishes a job in time. The slow version: node opening-slow.ts
import { bench } from "./bench.ts";
// A job is a list of tasks, each with a number of records, and a time limit in minutes.
export type Job = { records: number[]; limit: number };
// 1,000 tasks of 1 to maxRecords records each; the limit is 2 minutes per task.
export function makeJob(maxRecords: number): Job {
const records = Array.from({ length: 1000 }, () => 1 + Math.floor(Math.random() * maxRecords));
return { records, limit: 2 * records.length };
}
// Minutes the job takes when a worker handles `size` records per minute, one task at a time.
// A part-full batch still takes a whole minute. O(n) for n tasks.
export function minutesFor(records: number[], size: number): number {
let minutes = 0;
for (const r of records) minutes += Math.ceil(r / size);
return minutes;
}
// Try 1, 2, 3, ... until a size fits. O(n * answer) time, O(1) memory.
export function smallestBatchSlow({ records, limit }: Job): number {
if (records.length > limit) throw new RangeError("no size fits: every task needs at least a minute");
for (let size = 1; ; size++) if (minutesFor(records, size) <= limit) return size;
}
if (process.argv[1] === import.meta.filename) {
const job = { records: [9, 4, 7, 2, 6], limit: 10 };
console.log("records 9 4 7 2 6, limit 10 minutes -> size", smallestBatchSlow(job));
// The sizes are M, the largest number of records a task can have.
bench("smallestBatchSlow (n is M)", [250_000, 500_000, 1_000_000], makeJob, smallestBatchSlow);
}
In one run, it took about 930 ms when the largest task had a million records. Each time that number doubled, so did the time.
The function is correct, but it checks hundreds of thousands of sizes that one well-chosen check could rule out. This module teaches binary search, first on sorted data and then on the answer itself. Then it makes greedy choices on intervals, and shows how to test a greedy rule before you trust it.
After this module, you can:
- find the first item at or after a value in a sorted array in O(log n), and count the items in a range
- find the smallest value that passes a yes-or-no check, with binary search on the answer
- pick a greedy rule for an interval problem, and break a wrong rule with a search for counterexamples
- say why “earliest end first” fits the most meetings in one room
Measure trying every size
Make a folder for the module, as in Module 1, and copy bench.ts into it unchanged:
mkdir module-09 && cd module-09 && echo '{ "type": "module" }' > package.json
makeJob(M) gives each task 1 to M records, and the limit is 2 minutes per task. With that limit, the answer is about a third of M. At a size of M / 3, a task of up to M records takes 1, 2 or 3 minutes, 2 on average.
Pause and predict. The benchmark’s n column is M, the largest task, and the number of tasks stays 1,000. With M at 250,000, 500,000 and 1,000,000, how does the time grow?
Here is what node opening-slow.ts printed:
records 9 4 7 2 6, limit 10 minutes -> size 4
smallestBatchSlow (n is M)
n median ms x prev
250,000 223.82
500,000 450.87 2.0
1,000,000 925.68 2.1
Every table in this module comes from one run on an Intel Core i7-9750H laptop (x86_64, 6 cores, macOS) with Node.js 26.13.1. Your numbers will differ, but the ratios should look alike.
The time doubled with M. Each try costs one pass over the n tasks, and the loop makes about M / 3 tries. So smallestBatchSlow is O(n · M) time and O(1) memory. In other words, with 1,000 tasks fixed, twice the largest task means twice the tries and twice the time.
Rule: When the answer is a number in a range, count the candidates you check, not only the cost of one check.
A bigger batch never takes longer
Look at the sizes from the side of the answer. Figure 1 lists the minutes for every size on a job of five tasks, with 9, 4, 7, 2 and 6 records and a limit of 10 minutes. It is what trace-demo.ts prints.
size 1 2 3 4 5 6 7 8 9
minutes 28 15 11 9 8 7 6 6 5
fits? no no no yes yes yes yes yes yes
Figure 1: the “fits?” row is all “no” and then all “yes”, so the answer is the place where it switches.
A bigger batch can never make a task take more minutes, so once a size fits, every larger size fits too. A yes-or-no check is monotone when, as its input grows, it switches from false to true at most once and never back.
So “the smallest size that fits” is “the first yes in a sorted row of no and yes”. You don’t need to read the row from the left. A check at size 5 says “yes” and rules out 6 to 9 at once, and a check at size 3 says “no” and rules out 1 and 2.
That is binary search. The next sections show it on a sorted array first, where the row is easier to see.
Binary search on a sorted array
Suppose you have a log of request times, sorted from earliest, and you need the first request at or after time t. A scan from the start reads every earlier request, so each lookup is O(n).
Binary search finds a place in sorted data by checking the middle of the range where the answer can be. Then it drops the half that can’t hold it. Each check halves the range, so a million items need at most 20 checks.
In general that’s about log₂ n checks for n items. Here log₂ n is the number of times you can halve n before one item is left: 3 for 8 items, 20 for a million.
This module writes every binary search on a half-open range [lo, hi), which includes lo and excludes hi. The loop keeps one promise. Every index before lo is too small, and every index from hi on is big enough.
At the start nothing is known, so lo = 0 and hi = a.length, one past the last index. Each check moves one of them to the middle. When lo and hi meet, the place between the two sides is found.
The lower and the upper bound
There are two places you usually want in sorted data. The lower bound of t is the first index whose value is at least t. The upper bound of t is the first index whose value is more than t. Both are a.length when no value qualifies, which also means “not found”.
Figure 2 traces lowerBound on 1 3 7 7 7 9 for 7, as trace-demo.ts prints it. The array row has the indexes under it, and index 6 is one past the end.
step lo hi mid a[mid] a[mid] < 7? then
1 0 6 3 7 no hi = 3
2 0 3 1 3 yes lo = 2
3 2 3 2 7 no hi = 2
lo = hi = 2:
[1] [3] [7] [7] [7] [9]
0 1 2 3 4 5 6
^lo, hi
Figure 2: the first check lands on a 7, but not the first 7, so the search keeps going left until lo and hi meet at index 2.
upperBound differs in one comparison: it moves lo past values equal to the target too. Figure 3 traces it on the same array.
step lo hi mid a[mid] a[mid] <= 7? then
1 0 6 3 7 yes lo = 4
2 4 6 5 9 no hi = 5
3 4 5 4 7 yes lo = 5
lo = hi = 5:
[1] [3] [7] [7] [7] [9]
0 1 2 3 4 5 6
^lo, hi
Figure 3: <= instead of < pushes lo past every 7, so the search ends at 5, the first value above 7.
Here are the two bounds from bounds.ts. The full file in the lab folder also builds sorted logs of n request times and times 1,000 lookups on them, with a scan and with lowerBound.
// bounds.ts (excerpt): the two bounds
// The first index whose value is >= target, or a.length if there is none. O(log n), O(1) memory.
export function lowerBound(a: number[], target: number): number {
let lo = 0, hi = a.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (a[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
// The first index whose value is > target, or a.length if there is none. O(log n), O(1) memory.
export function upperBound(a: number[], target: number): number {
let lo = 0, hi = a.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (a[mid] <= target) lo = mid + 1;
else hi = mid;
}
return lo;
}
Each step of either loop halves hi - lo, so lowerBound and upperBound are O(log n) time and O(1) memory. The file has two scans to compare, one with findIndex and one with a plain loop. A scan is O(n) per lookup, so q lookups cost O(q · n), against O(q log n) for the bound.
Pause and predict. At 100,000, 200,000 and 400,000 requests, how much does each doubling add to 1,000 scans, and to 1,000 binary searches?
node bounds.ts printed:
a = 1 3 7 7 7 9
lowerBound(a, 7): 2 upperBound(a, 7): 5
lowerBound(a, 4): 2 lowerBound(a, 10): 6
same answers: true
findIndex, 1,000 lookups
n median ms x prev
100,000 354.19
200,000 712.15 2.0
400,000 1452.54 2.0
plain loop, 1,000 lookups
n median ms x prev
100,000 18.18
200,000 36.63 2.0
400,000 72.27 2.0
lowerBound, 1,000 lookups
n median ms x prev
100,000 0.21
200,000 0.23 1.1
400,000 0.30 1.3
Both scans doubled with n, as O(q · n) predicts. At 400,000 requests, the plain loop took 72.27 ms and lowerBound 0.30 ms.
lowerBound grew 1.1 and then 1.3 times, where log₂ n predicts about 1.06 per doubling. These times are a fraction of a millisecond, so one slow run moves the median of five.
Why was findIndex about 20 times slower than the plain loop, when both read the same elements? That’s the engine’s compiler, not the algorithm. Both scans are O(n) per lookup, and both lose to a binary search. “Going deeper” shows what the compiler did.
Rule: Keep the promise of the range: before
lois too small, fromhion is big enough. Thenlo = mid + 1andhi = midfollow from it.
Binary search on the answer
Now go back to the batch size. The sizes 1 to M are a sorted range, and “fits?” is monotone over it. So the same loop finds the first size that fits, with minutesFor as the check instead of an array read.
Binary search on the answer is a binary search over the possible answers of a problem, using a monotone check in place of a sorted array. The range here includes both ends, [lo, hi], because hi is a real size that always fits. It starts at the largest task, so each task takes one minute, and the job takes n minutes, within the limit. Save opening-fast.ts:
// The smallest batch size with binary search on the answer: node opening-fast.ts
import { bench } from "./bench.ts";
import { type Job, makeJob, minutesFor, smallestBatchSlow } from "./opening-slow.ts";
// Every size below the answer is too small, and every size from it up fits.
// Search [lo, hi]: lo is never above the answer, and hi always fits.
// O(n log M) time for n tasks and the largest task M. O(1) memory.
export function smallestBatchFast({ records, limit }: Job): number {
if (records.length > limit) throw new RangeError("no size fits: every task needs at least a minute");
let lo = 1, hi = 1;
for (const r of records) if (r > hi) hi = r; // one batch per task: n minutes, which fits
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (minutesFor(records, mid) <= limit) hi = mid; // mid fits: the answer is mid or smaller
else lo = mid + 1; // mid is too small, and so is everything below it
}
return lo;
}
if (process.argv[1] === import.meta.filename) {
const job = makeJob(5_000);
console.log("same answer:", smallestBatchSlow(job), smallestBatchFast(job));
const sizes = [250_000, 500_000, 1_000_000];
bench("smallestBatchSlow (n is M)", sizes, makeJob, smallestBatchSlow);
bench("smallestBatchFast (n is M)", sizes, makeJob, smallestBatchFast);
bench("smallestBatchFast, larger (n is M)", [1e9, 1e12, 1e15], makeJob, smallestBatchFast);
}
Figure 4 traces it on the five tasks from Figure 1, as trace-demo.ts prints it.
lo hi mid minutes(mid) fits? then
1 9 5 8 yes hi = 5
1 5 3 11 no lo = 4
4 5 4 9 yes hi = 4
lo = hi = 4: the answer
Figure 4: three checks find the size that smallestBatchSlow found in four tries, and M sizes need about log₂ M checks.
Each check costs one pass over the n tasks, and there are about log₂ M checks. So smallestBatchFast is O(n log M) time and O(1) memory.
Pause and predict. At M = 10¹⁵, a million billion records, how long does smallestBatchFast take, against about 0.06 ms at M = 1,000,000?
node opening-fast.ts runs both versions on the same sizes, then the fast one on much larger tasks:
same answer: 1737 1737
smallestBatchSlow (n is M)
n median ms x prev
250,000 225.78
500,000 472.71 2.1
1,000,000 926.10 2.0
smallestBatchFast (n is M)
n median ms x prev
250,000 0.08
500,000 0.06 0.8
1,000,000 0.06 1.0
smallestBatchFast, larger (n is M)
n median ms x prev
1,000,000,000 0.09
1,000,000,000,000 0.32 3.7
1,000,000,000,000,000 0.27 0.8
At M = 1,000,000, the time went from 926.10 ms to 0.06 ms. Figure 5 draws both.
median ms for the smallest batch size, 1,000 tasks (each # is about 21 ms)
M = 250,000 slow ########### 225.78
fast | 0.08
M = 500,000 slow ####################### 472.71
fast | 0.06
M = 1,000,000 slow ############################################ 926.10
fast | 0.06
Figure 5: trying every size grows with M, while the binary search stays near 0.06 ms because log₂ M grows by only one per doubling.
The fast version did not change from 250,000 to 1,000,000, where log₂ M goes from 18 to 20. At M = 10¹⁵ it needs about 50 checks, and it took 0.27 ms. The jump from 10⁹ to 10¹² is larger than its extra checks explain (40 against 30), and “Going deeper” shows where it comes from.
The pattern has one condition. The check must be monotone, because the search never looks at the sizes it rules out. If the check can switch back to “no”, the search still returns a number, and nothing tells you it’s wrong.
Rule: If a yes-or-no check on a number switches from no to yes once, binary search finds the switch in O(log range) checks.
Greedy choices: the most meetings in one room
Here is a different kind of problem. One meeting room gets a list of meeting requests, and you want to fit as many meetings as you can. A meeting is a half-open range of minutes [start, end), so one that ends at 10 and one that starts at 10 fit together.
The slow answer tries every subset of the requests and keeps the largest one with no overlaps. That’s 2ⁿ subsets, so each extra meeting doubles the work.
A greedy algorithm builds its answer one choice at a time, takes the choice that looks best right now, and never undoes it. For the room, it puts the meetings in some order, then takes each one that fits after the ones already taken. The whole question is which order. Four orders sound reasonable:
- the earliest start
- the shortest meeting
- the meeting with the fewest overlaps
- the earliest end
meetings.ts in the lab folder holds the brute force, mostMeetingsBrute, and the greedy rule this module uses, the earliest end. Here is the greedy rule:
// meetings.ts (excerpt): the greedy rule
// A meeting is half-open [start, end): one that ends at 10 and one that starts at 10 fit together.
export type Meeting = [start: number, end: number];
// Greedy: sort by end, take each meeting that starts once the room is free.
// O(n log n) time for the sort, O(n) memory for the sorted copy and the result.
export function mostMeetings(ms: Meeting[]): Meeting[] {
const taken: Meeting[] = [];
let free = -Infinity; // when the room is free again
for (const m of ms.toSorted((a, b) => a[1] - b[1])) {
if (m[0] >= free) {
taken.push(m);
free = m[1];
}
}
return taken;
}
toSorted sorts a copy and leaves the caller’s array alone. Figure 6 traces mostMeetings on the file’s demo day, as trace-demo.ts prints it. free is the minute the room is free again.
meeting free from start >= free? taken
[9, 11) - yes [9, 11)
[10, 12) 11 no [9, 11)
[11, 13) 11 yes [9, 11) [11, 13)
[13, 15) 13 yes [9, 11) [11, 13) [13, 15)
[12, 16) 15 no [9, 11) [11, 13) [13, 15)
[9, 17) 15 no [9, 11) [11, 13) [13, 15)
Figure 6: each meeting needs one comparison with free, and the long meeting from 9 to 17, which ends last, is checked last and skipped.
The sort is O(n log n) and the pass is O(n), so mostMeetings is O(n log n) time. It uses O(n) memory for the sorted copy and the result. The brute force is O(2ⁿ · n log n), because it filters and sorts each of the 2ⁿ subsets. node meetings.ts printed:
mostMeetings: [[9,11],[11,13],[13,15]] brute force: 3
mostMeetingsBrute
n median ms x prev
12 2.51
14 7.59 3.0
16 34.12 4.5
mostMeetings
n median ms x prev
250,000 101.02
500,000 195.85 1.9
1,000,000 425.17 2.2
The brute force grew 3.0 and 4.5 times for every two more meetings, near the 4 times that 2ⁿ predicts. It took 34.12 ms for only 16 meetings. The greedy rule handled a million meetings in 425.17 ms, and it grew about 2 times per doubling.
Try to break a greedy rule before you trust it
A greedy rule is easy to write and easy to get wrong, because a wrong rule gives a plausible answer with no error. So before you trust one, try to break it.
A counterexample is an input where the rule’s answer is wrong. The brute force gives the right answer on small inputs, so a search for counterexamples is a loop. Make a small random day, run the rule and the brute force, and stop when they differ.
greedy-check.ts in the lab folder runs that search for all four orders. It has three parts:
rules, one greedy function for each orderrandomMeetings, which makes a day of 1 to 8 random meetingsshrink, which drops one meeting at a time while the rule still fails
Shrinking a counterexample makes it as small as it can be, so you can check it by hand. Here is the loop that ties the parts together:
// greedy-check.ts (excerpt): the search for counterexamples
for (const [name, rule] of Object.entries(rules)) {
let found = "no counterexample in 100,000 tries";
for (let t = 0; t < 100_000; t++) {
const ms = randomMeetings();
const g = rule(ms), b = mostMeetingsBrute(ms);
if (g !== b) {
const small = shrink(ms, rule);
found = `try ${t + 1}: ${JSON.stringify(small)} greedy ${rule(small)}, best ${mostMeetingsBrute(small)}`;
break;
}
}
console.log(`${name.padEnd(16)} ${found}`);
}
Pause and predict. Which of the four orders survives 100,000 random days of up to eight meetings?
node greedy-check.ts printed, in about 1.9 seconds:
earliest start try 16: [[16,17],[17,23],[15,23]] greedy 1, best 2
shortest first try 36: [[13,15],[14,22],[12,14]] greedy 1, best 2
fewest overlaps try 5333: [[11,15],[7,11],[6,8],[8,13],[3,7],[13,16],[1,4]] greedy 3, best 4
earliest end no counterexample in 100,000 tries
coins [1,5,10,25] no counterexample for amounts 1..500
coins [1,3,4] amount 6: greedy 3 coins, best 2
The days are random, so your tries and meetings will differ. The last two lines check a rule for making change, which “Going deeper” explains.
“Earliest start” failed on try 16, with three meetings you can check by hand. It takes [15, 23) first, and then neither [16, 17) nor [17, 23) fits. The best plan takes those two.
“Shortest first” failed with three meetings too. Its two shortest meetings, [13, 15) and [12, 14), overlap each other. The first one taken, [13, 15), blocks both others.
“Fewest overlaps” lasted 5,333 tries, and its smallest counterexample has seven meetings. In two more runs it failed at try 2,046 and try 5,120, each time with seven meetings. So a short search, or the three examples you try by hand, can miss a wrong rule. “Earliest end” had no counterexample in 100,000 tries.
This search has a cost. The brute force is exponential, so keep the random inputs small, up to about 15 items. Small inputs are enough for most wrong rules, as the three-meeting counterexamples show.
Rule: Before you trust a greedy rule, run it against a brute force on thousands of small random inputs. Passing is evidence, not proof.
Why the earliest end is safe
A search that finds nothing is not a proof, so here is why “earliest end” is always right. The proof below follows chapter 4 of Kevin Wayne’s lecture slides for Kleinberg and Tardos’s Algorithm Design.
An exchange argument takes any best answer and changes it, one choice at a time, into the greedy answer, without making it worse.
Take any plan with the most meetings, sorted by time, and call its first meeting o1. The greedy rule’s first meeting g1 ends first of all the meetings, so it ends no later than o1.
Swap o1 for g1. The plan still has no overlaps, because o1 ended by the time the second meeting started, and g1 ends no later. It also has the same count. Figure 7 draws the swap on a plan of three meetings.
minute 9 10 11 12 13 14 15 16
a best plan [ o1 )[ o2 )[ o3 )
greedy first [ g1 )
after swap [ g1 ) [ o2 )[ o3 )
Figure 7: g1 ends no later than o1, so it fits wherever o1 fit, and the plan keeps its three meetings.
Now repeat the argument on the meetings that start after g1 ends. The greedy rule’s second meeting ends first among those, so it can replace the plan’s second meeting, and so on. At the end, the best plan has become the greedy plan with no meeting lost. So the greedy plan has the most meetings.
The proof also shows when the rule stops working. Suppose each meeting has a value, and you want the most value. A valuable meeting can overlap the one that ends first, so the swap can lose value, and the problem needs Module 11‘s dynamic programming.
More shapes of the two patterns
Both patterns show up in a few more shapes, each with a sign in the problem that points to it. Save variations.ts:
// Two more shapes: a count with two bounds, and merging intervals: node variations.ts
import { lowerBound, upperBound } from "./bounds.ts";
import type { Meeting } from "./meetings.ts";
// How many values of a sorted array fall in [from, to], both ends included. O(log n), O(1) memory.
export function countBetween(a: number[], from: number, to: number): number {
if (from > to) return 0;
return upperBound(a, to) - lowerBound(a, from);
}
// Merge busy times into blocks: sort by start, then extend the last block while the
// next interval starts inside it. Half-open, so [8, 10) and [10, 12) stay apart.
// O(n log n) time, O(n) memory.
export function mergeBusy(ms: Meeting[]): Meeting[] {
const out: Meeting[] = [];
for (const [start, end] of ms.toSorted((a, b) => a[0] - b[0])) {
const last = out.at(-1);
if (last && start < last[1]) last[1] = Math.max(last[1], end);
else out.push([start, end]);
}
return out;
}
if (process.argv[1] === import.meta.filename) {
const a = [1, 3, 7, 7, 7, 9];
console.log("countBetween(a, 3, 7):", countBetween(a, 3, 7), " bounds:", lowerBound(a, 3), upperBound(a, 7));
console.log("countBetween(a, 4, 6):", countBetween(a, 4, 6), " bounds:", lowerBound(a, 4), upperBound(a, 6));
console.log("mergeBusy:", JSON.stringify(mergeBusy([[8, 10], [1, 3], [2, 6], [15, 18], [10, 12]])));
}
Pause and predict. On the array 1 3 7 7 7 9, what do the two bounds return for a range from 4 to 6, which holds no value?
node variations.ts printed:
countBetween(a, 3, 7): 4 bounds: 1 5
countBetween(a, 4, 6): 0 bounds: 2 2
mergeBusy: [[1,6],[8,10],[10,12],[15,18]]
Count in a range with two bounds
The count of values from from to to, both included, is the upper bound of to minus the lower bound of from. In 1 3 7 7 7 9, that’s 5 − 1 = 4 for 3 to 7. For 4 to 6, both bounds land on index 2, the place where 4 to 6 would go, and the count is 0.
Two binary searches make it O(log n), whatever the size of the range, where filter takes O(n). The sign is “how many between a and b” on sorted data that doesn’t change.
Merge busy times
To merge busy times into blocks, sort by start and extend the last block while the next interval starts inside it. Figure 8 traces mergeBusy, as trace-demo.ts prints it.
interval last block start < block end? blocks
[1, 3) - no block yet [1, 3)
[2, 6) [1, 3) yes: extend [1, 6)
[8, 10) [1, 6) no: new block [1, 6) [8, 10)
[10, 12) [8, 10) no: new block [1, 6) [8, 10) [10, 12)
[15, 18) [10, 12) no: new block [1, 6) [8, 10) [10, 12) [15, 18)
Figure 8: after the sort, an interval can only touch the last block, so one pass merges everything in O(n) after an O(n log n) sort.
[8, 10) and [10, 12) stay separate because they are half-open and only touch. If the problem says a meeting ending at 10 and one starting at 10 overlap, change start < last[1] to start <= last[1]. The sign is a request to merge intervals, or to find the free time between them.
How many at once
The depth of a set of intervals is the largest number of them that contain the same moment. It is the number of rooms a day of meetings needs. The slides prove that you reach it if you sort by start and reuse the room that is free first.
To find that room fast, keep the end time of each room in use in a min-heap. A min-heap, built in Module 8, always gives you its smallest item, and adding or removing one costs O(log n). That’s Exercise 5, and the sign is “how many rooms” or “the most at the same time”.
Each interval shape sorts by a different end. Sort by end to keep the most intervals, and by start to merge intervals or count rooms. And decide first whether touching intervals overlap.
Underneath: binary search in JavaScript
JavaScript has no binary search
As of November 2026, the current draft of the JavaScript specification, ECMA-262, has no binary search for arrays. TC39, the committee that changes the language, has no proposal for one in its list of proposals. The array methods that find an item, such as indexOf and findIndex, all scan. So they are O(n) even on a sorted array, and you write lowerBound yourself.
Sorting costs O(n log n), so for one lookup a scan is cheaper. For many lookups on data that doesn’t change, sort once and search. For many lookups by exact key, a Map (Module 3) is O(1) and needs no order. Binary search wins when the question is about order: “the first at or after”, “how many between”.
A sorted array also changes slowly. Inserting in the middle shifts every later item, O(n), as Module 4 measured for splice. So a sorted array suits data that changes rarely, which Module 6 also said when it compared it with a binary search tree.
Why the middle is lo + Math.floor((hi - lo) / 2)
In 2006, Joshua Bloch reported a bug that had sat for about nine years in the binary search of Java’s java.util.Arrays (Google Research blog). The middle was (low + high) / 2. For arrays of 2³⁰ or more elements, that sum went past the largest 32-bit integer and turned negative. One of his fixes was (low + high) >>> 1.
In JavaScript, that fix is the bug. >>> first turns its left side into an unsigned 32-bit integer, so a sum of 2³² or more wraps: it loses its high bits and becomes a much smaller number. Array indexes never get that large, but a binary search on the answer can, because its range holds values.
So this module writes lo + Math.floor((hi - lo) / 2) everywhere. JavaScript numbers hold every integer up to 2⁵³ − 1 exactly, and this form never goes above hi. “Going deeper” runs both forms on a search where >>> 1 never ends.
Common mistakes
mistakes.ts writes five bugs that are easy to make with binary search and intervals, and prints what each one returns. Run node mistakes.ts:
1. lo = mid: stuck at lo=2 hi=3
2. stop at first match: 2 lowerBound: 0
3. lowerBound on unsorted for 3: 2 (3 is at index 3)
4. hi = length - 1, first >= 9 in [1,3,5]: 2 lowerBound: 3
5. with s > free: 2 meetings (expected 3)
lo = mid instead of lo = mid + 1. When hi = lo + 1, the middle is lo again, so the range never shrinks. The search for 6 in 1 3 5 7 got stuck at lo = 2, hi = 3, and only the step cap ended it. In the “too small” branch, mid is known to be too small, so move lo past it.
Stopping at the first match. A search that returns as soon as a[mid] === target returns some matching index, not the first. In 7 7 7 7 9 it returned 2. If repeats are possible and you need the first or the count, use the lower and upper bounds.
Binary search on data that is not sorted. There is no error. lowerBound on 5 1 9 3 7 returned 2 for the value 3, which is at index 3. Sort first, or check that the data is sorted where it comes in.
hi = a.length - 1 with a half-open loop. The range [0, a.length - 1) leaves out the answer “none”. The first value of at least 9 in 1 3 5 came back as index 2, a value of 5, instead of 3, meaning “not found”. Start with hi = a.length, one past the end.
Closed intervals where the problem means half-open. With s > free, a meeting that starts at 10 doesn’t fit after one that ends at 10. So only 2 of 3 touching meetings were taken. Decide whether touching intervals overlap before you write the comparison, and write it in a comment.
Two more mistakes came up earlier in the module. One is (lo + hi) >>> 1 copied from Java, which wraps above 2³². The other is trusting a greedy rule because it worked on the examples you tried by hand.
Exercises
The exercises are in the module’s exercises folder, each with a test file, and the solutions are in solutions. Exercise 5 imports the Heap from Module 8, so keep module-08 next to module-09. Run all the tests with:
node --test "exercises/*.test.ts"
All 22 tests fail until you write the five answers. Each exercise ends with a test that a correct but slow answer fails, on time or on the number of checks. The slow folder holds such answers, with a copy of each test.
Exercise 1: the first bad build (easy)
Builds are numbered 1 to count. A change broke the tests at some build, so from that build on every build is bad. isBad(build) runs the tests on one build, and each run is slow.
Write firstBadBuild(count, isBad): the first bad build, or count + 1 if every build is good. Start from exercises/first-bad-build.ts:
// Exercise 1: builds are numbered 1 to count. Once a build is bad, every later build is bad too.
// isBad(build) runs the tests on one build. Returns the first bad build, or count + 1 if every
// build is good, with as few calls to isBad as you can.
export function firstBadBuild(count: number, isBad: (build: number) => boolean): number {
throw new Error("not implemented");
}
For 10 builds where build 7 is the first bad one, the answer is 7. The tests also check all bad, all good, one build, no builds, and every possible first bad build for counts up to 40. Their isBad fails on a build number outside 1 to count. The last test has a billion builds and allows at most 31 calls to isBad.
Hint
isBad is monotone over the build numbers. Which half-open range of builds holds the answer at the start, if “every build is good” must be a possible answer too?
Solution
// Exercise 1: builds are numbered 1 to count. Once a build is bad, every later build is bad too.
// isBad(build) runs the tests on one build. Returns the first bad build, or count + 1 if every
// build is good, with as few calls to isBad as you can.
// Binary search on the build number over the half-open range [1, count + 1).
// O(log count) calls to isBad, O(1) memory.
export function firstBadBuild(count: number, isBad: (build: number) => boolean): number {
let lo = 1, hi = count + 1; // every build before lo is good; hi is bad, or past the last build
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (isBad(mid)) hi = mid;
else lo = mid + 1;
}
return lo;
}
Cost: the range starts with count + 1 builds and halves at each call, so O(log count) calls to isBad and O(1) memory. For a billion builds that’s at most 30 calls. Testing the builds in order, as slow/first-bad-build.ts does, is O(count) calls, and it failed the last test with “used more than 31 tests”.
Exercise 2: the version that was live (easy)
A list of releases is sorted by time, oldest first, and each has a time at and a version. Write versionAt(releases, t): the version that was live at time t, which is the last release at or before t. If two releases have the same time, the later one in the list wins, and before the first release the answer is undefined. Start from exercises/version-at.ts:
// Exercise 2: `releases` is sorted by time, oldest first. Returns the version that was live at
// time t: the last release at or before t. Two releases at the same time: the later one in the
// list wins. Returns undefined before the first release.
export type Release = { at: number; version: string };
export function versionAt(releases: Release[], t: number): string | undefined {
throw new Error("not implemented");
}
Take releases 1.0 at 100, 1.1 and 1.2 at 250, and 2.0 at 400. The version at 120 is 1.0, at 250 it is 1.2, and at 99 there is none. The tests also check an empty list and 200 random lists against a scan. The last test makes 20,000 lookups in 20,000 releases in under 100 ms.
Hint
The last release at or before t sits right before the first release after t. Which bound finds “the first release after t”?
Solution
// Exercise 2: `releases` is sorted by time, oldest first. Returns the version that was live at
// time t: the last release at or before t. Two releases at the same time: the later one in the
// list wins. Returns undefined before the first release.
export type Release = { at: number; version: string };
// The upper bound of t on the release times, minus one.
// O(log n) time, O(1) memory.
export function versionAt(releases: Release[], t: number): string | undefined {
let lo = 0, hi = releases.length; // before lo: at <= t; from hi on: at > t
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (releases[mid].at <= t) lo = mid + 1;
else hi = mid;
}
return lo > 0 ? releases[lo - 1].version : undefined;
}
Cost: one upper bound on the release times, O(log n) time and O(1) memory. Releases with the same time sit together, and the upper bound lands after all of them, so the one before it is the last in the list. Scanning back from the end with findLast, as slow/version-at.ts does, is O(n) per lookup: it took 1,610 ms on the last test.
Exercise 3: the fewest health checks (medium)
Each job has a maintenance window [start, end] of whole minutes, and here both ends are included. A health check at minute m covers every job whose window contains m. Write fewestChecks(windows): the fewest checks that cover every job. Start from exercises/fewest-checks.ts:
// Exercise 3: each job has a maintenance window [start, end] of whole minutes, both ends
// included. A health check at minute m covers every job whose window contains m. Returns the
// fewest checks that cover every job.
export function fewestChecks(windows: [number, number][]): number {
throw new Error("not implemented");
}
For windows [3, 6], [1, 4] and [7, 9], the answer is 2: a check at minute 4 covers the first two. The tests also check windows that share one minute, a one-minute window, nested windows and no jobs. Another test compares 100 random days with trying every set of minutes from 0 to 11. The last test covers 20,000 jobs in under 100 ms.
Hint
Look at the window that ends first. Some check must fall inside it. Which minute in it covers the most of the other windows? Then sort, as mostMeetings does, and remember that both ends count.
Solution
// Exercise 3: each job has a maintenance window [start, end] of whole minutes, both ends
// included. A health check at minute m covers every job whose window contains m. Returns the
// fewest checks that cover every job.
// Greedy, earliest end first: a window that no check covers yet gets a check at its end,
// the latest minute that still covers it. O(n log n) time, O(n) memory for the sorted copy.
export function fewestChecks(windows: [number, number][]): number {
let checks = 0, last = -Infinity; // the minute of the latest check
for (const [start, end] of windows.toSorted((a, b) => a[1] - b[1])) {
if (start > last) { // the latest check came before this window opened
checks++;
last = end;
}
}
return checks;
}
Cost: O(n log n) time for the sort and O(n) memory for the sorted copy. The window that ends first needs a check inside it. Its end covers every window that an earlier check in it would cover, because no window ends sooner. The same exchange argument as for mostMeetings then repeats on the windows left.
Finding the next window with a scan and marking the covered ones with another scan, as slow/fewest-checks.ts does, is O(n · checks): it took 1,331 ms on the last test.
Exercise 4: the smallest largest batch (medium)
Files must be uploaded in their given order, in at most k batches, and each batch is a run of files next to each other. Write smallestMaxBatch(files, k): the smallest possible size of the largest batch. Start from exercises/smallest-max-batch.ts:
// Exercise 4: upload files in their given order in at most k batches; each batch is a run of
// consecutive files. Returns the smallest possible size of the largest batch.
export function smallestMaxBatch(files: number[], k: number): number {
throw new Error("not implemented");
}
For files 7, 2, 5, 10 and 8 in 2 batches, the answer is 18: 7 2 5 and 10 8. The tests also check one file, no files, more batches than files, and 300 random cases against trying every way to cut the list. One test has files of 3 × 10¹² and 10¹² bytes, so a midpoint that wraps above 2³² fails it. The last test splits 1,000 files into 4 batches in under 50 ms.
Hint
For a given limit, can you say quickly whether k batches are enough? Fill each batch until the next file would go over the limit. A larger limit never needs more batches. What are the smallest and largest limits that can be the answer?
Solution
// Exercise 4: upload files in their given order in at most k batches; each batch is a run of
// consecutive files. Returns the smallest possible size of the largest batch.
// Binary search on the answer: a limit works if a greedy pass (fill each batch until the next
// file would go over) needs at most k batches. O(n log S) time for S = total size, O(1) memory.
export function smallestMaxBatch(files: number[], k: number): number {
const batchesNeeded = (limit: number): number => {
let batches = 1, current = 0;
for (const f of files) {
if (current + f > limit) { // f starts a new batch
batches++;
current = 0;
}
current += f;
}
return batches;
};
let lo = 0, hi = 0;
for (const f of files) {
lo = Math.max(lo, f); // a batch must hold the largest file
hi += f; // one batch holds everything
}
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (batchesNeeded(mid) <= k) hi = mid;
else lo = mid + 1;
}
return lo;
}
Cost: the answer lies between the largest file and the total size S, so the search makes O(log S) checks of O(n) each. That’s O(n log S) time and O(1) memory. Filling each batch as far as it goes is safe, because after any number of batches the greedy pass has placed at least as many files as any other split. So it never needs more batches.
Trying every limit from the largest file up, as slow/smallest-max-batch.ts does, is the opening’s slow loop again, O(n · (answer − largest file)). It took 1,667 ms on the last test.
Exercise 5: rooms for a day of meetings (harder)
Write roomsNeeded(meetings): the number of rooms a day of meetings needs. Meetings are half-open [start, end), so a meeting that ends at 10 and one that starts at 10 can share a room. Start from exercises/rooms-needed.ts:
// Exercise 5: how many rooms does a day of meetings need? Meetings are half-open
// [start, end), so a meeting that ends at 10 and one that starts at 10 can share a room.
// You may import the Heap from "../../module-08/heap.ts".
export function roomsNeeded(meetings: [number, number][]): number {
throw new Error("not implemented");
}
For meetings [9, 12), [10, 11), [11, 13) and [12, 14), the answer is 2. The tests also check no meetings, touching meetings, three equal meetings and 300 random days against the depth, counted at every start. The last test places 100,000 meetings in under 200 ms.
Hint
Sort by start. When a meeting starts, the only room worth checking is the one that is free first. Which structure from Module 8 always knows its smallest end time?
Solution
// Exercise 5: how many rooms does a day of meetings need? Meetings are half-open
// [start, end), so a meeting that ends at 10 and one that starts at 10 can share a room.
// You may import the Heap from "../../module-08/heap.ts".
// Sort by start. A min-heap holds the end time of each room in use, and its top is the room
// that is free first. O(n log n) time, O(n) memory.
import { Heap } from "../../module-08/heap.ts";
export function roomsNeeded(meetings: [number, number][]): number {
const ends = new Heap<number>((a, b) => a < b);
for (const [start, end] of meetings.toSorted((a, b) => a[0] - b[0])) {
if (ends.size > 0 && ends.peek()! <= start) ends.replaceTop(end); // reuse the room free first
else ends.push(end); // every room is busy: open a new one
}
return ends.size;
}
Cost: O(n log n) for the sort, then one heap operation per meeting at O(log n). So O(n log n) time and O(n) memory, for the sorted copy and the heap. Scanning every room for a free one, as slow/rooms-needed.ts does, is O(n · rooms): it took 843 ms on the last test.
Going deeper
You can skip this section. It covers the measurements and engine details that the main path left out.
Why findIndex was 20 times slower than a loop
V8 is the JavaScript engine in Node.js. It compiles a function that runs often into faster machine code, in steps called tiers. TurboFan is its top tier, the optimizing compiler.
findIndex calls your function once for every element it reads. scan-tier.ts times ten rounds of 1,000 lookups with findIndex and with a plain loop. On Node.js 26.13.1 it printed:
findIndex ms: 361 360 364 360 363 362 370 374 376 370 (check 510)
loop ms: 20 19 19 19 19 19 19 19 19 19 (check 510)
The same file on Node.js 22.17.0:
findIndex ms: 366 358 355 20 14 14 15 14 14 14 (check 970)
loop ms: 58 48 48 48 51 50 50 48 48 49 (check 970)
On Node.js 22.17, the findIndex rounds dropped from about 360 ms to about 14 ms after three rounds, when TurboFan compiled the calling function. On Node.js 26.13.1 they stayed at 360 to 376 ms for all ten rounds. Running it with node --trace-opt scan-tier.ts shows why. The function that calls findIndex was compiled by Maglev and never reached TurboFan, while the loop reached TurboFan.
Maglev is V8’s middle tier, between its fast baseline compiler and TurboFan. It compiles quickly and aims for “good enough code, fast enough”, as the V8 blog post on Maglev puts it. So the tier a function reaches can change a scan’s time by 20 times between Node.js versions, while the cost class stays O(n) per lookup.
The midpoint bug, run
In Java, (low + high) / 2 overflows a 32-bit int. In JavaScript, the same line is not a bug, because numbers are doubles and every integer up to 2⁵³ − 1 (Number.MAX_SAFE_INTEGER) is exact. An array’s length is below 2³², as section 10.4.2 of ECMA-262 says, so the sum of two indexes stays far below 2⁵³.
The conversion that >>> does first is called ToUint32 in the specification, and Module 3‘s hash used it as >>> 0. midpoint.ts shows what it does to a midpoint:
// The midpoint bug from Java and C (Bloch, 2006), and what it becomes in JavaScript: node midpoint.ts
// 1. Plain addition is exact for every integer below 2^53, so this is safe
// for any array index and for most "binary search on the answer" ranges.
const lo = 3_000_000_000, hi = 4_000_000_000;
console.log("1. Math.floor((lo + hi) / 2):", Math.floor((lo + hi) / 2));
// 2. The Java fix (lo + hi) >>> 1 is a bug in JavaScript: >>> first turns
// its left side into a 32-bit unsigned integer, so a sum of 2^32 or more wraps.
console.log("2. (lo + hi) >>> 1:", (lo + hi) >>> 1, " (lo + hi) >> 1:", (lo + hi) >> 1, " ((lo + hi) / 2) | 0:", ((lo + hi) / 2) | 0);
// 3. A search on the answer with that midpoint: smallest x with x * x >= 10^19.
function sqrtCeil(target: number, mid: (lo: number, hi: number) => number): string {
let a = 0, b = 2 ** 33; // the answer lies in [0, 2^33]
for (let steps = 0; a < b; steps++) {
if (steps > 200) return `gave up after 200 steps, lo=${a} hi=${b}`;
const m = mid(a, b);
if (m * m >= target) b = m;
else a = m + 1;
}
return String(a);
}
console.log("3. with Math.floor:", sqrtCeil(1e19, (a, b) => a + Math.floor((b - a) / 2)));
console.log(" with >>> 1: ", sqrtCeil(1e19, (a, b) => (a + b) >>> 1));
// 4. Above 2^53, Numbers skip integers: lo + 1 can equal lo.
const big = 2 ** 53;
console.log("4. 2^53 + 1 === 2^53:", big + 1 === big, " Number.MAX_SAFE_INTEGER:", Number.MAX_SAFE_INTEGER);
node midpoint.ts printed:
1. Math.floor((lo + hi) / 2): 3500000000
2. (lo + hi) >>> 1: 1352516352 (lo + hi) >> 1: -794967296 ((lo + hi) / 2) | 0: -794967296
3. with Math.floor: 3162277661
with >>> 1: gave up after 200 steps, lo=1 hi=8589934592
4. 2^53 + 1 === 2^53: true Number.MAX_SAFE_INTEGER: 9007199254740991
Line 2 shows three ways to wrap. >>> gives a wrong positive middle, and >> and | 0 give a negative one. Line 3 searches for the smallest x with x² ≥ 10¹⁹ in [0, 2³³]. With Math.floor it finds 3,162,277,661, but with >>> 1 every middle wraps to 0, lo stays at 1, and the loop never ends.
Line 4 shows the limit of Math.floor too. Above 2⁵³, numbers skip integers, so mid + 1 can equal mid, and a search on answers that large can stop moving. For those, use BigInt.
Numbers above 2³¹ − 1 are not Smis
Module 2 showed that V8 stores small integers as Smis, inside the array slot, and larger numbers as doubles. The kind of slot V8 picks for an array’s items is its elements kind. smi-range.js asks V8 which numbers are Smis in this build. Run it with node --allow-natives-syntax smi-range.js:
1073741823 Smi
1073741824 Smi
2147483647 Smi
2147483648 not a Smi
-2147483648 Smi
-2147483649 not a Smi
records with M = 2e9, Smi elements: true
records with M = 4e9, Smi elements: false
The largest Smi here is 2³¹ − 1 = 2,147,483,647, and the smallest is −2³¹. V8 gives Smis 32 bits of value when a value takes 8 bytes, and 31 bits with pointer compression, which stores values in 4 bytes. You can read this in V8’s v8-internal.h in Node.js v26.13.1. Node.js 26 on x64 is built without pointer compression, as Module 1 said.
That’s where smallestBatchFast slowed down. With M = 4 × 10⁹, some tasks have more than 2³¹ − 1 records, so the records array holds doubles. smi-step.ts times the search around that limit with 21 runs per size, then times records up to 10⁹ forced into a double array:
pointer compression: 0
smallestBatchFast (n is M)
n median ms x prev
1,000,000,000 0.09
2,000,000,000 0.09 1.0
2,147,483,647 0.09 1.0
2,147,483,649 0.09 1.0
3,000,000,000 0.15 1.7
4,000,000,000 0.18 1.1
1,000,000,000,000 0.16 0.9
smallestBatchFast, records stored as doubles (n is M)
n median ms x prev
1,000,000,000 0.12
2,000,000,000 0.13 1.1
The time stayed at 0.09 ms up to M = 2³¹ + 1, where almost no task passes the limit. It stepped up between there and 3 × 10⁹. Forcing the same small records into a double array took them from 0.09 to 0.12 or 0.13 ms.
At 10¹², this run measured 0.16 ms, against 0.32 ms in opening-fast.ts with five runs, so part of that jump was noise. The elements kind explains about half of the step. The rest likely comes from the arithmetic on numbers above the 32-bit range, which this run did not measure on its own. The cost class stays O(n log M) either way.
A greedy rule for coins
The last two lines of greedy-check.ts check a second greedy rule: pay an amount with the fewest coins by taking the largest coin that fits each time. The check tries every amount from 1 to 500.
With coins of 1, 5, 10 and 25, the largest coin first was always right. With coins of 1, 3 and 4, it failed at 6. It paid 4 + 1 + 1, three coins, where 3 + 3 is two. The right answers come from coinsBest, which builds the fewest coins for every amount from smaller amounts, a table that Module 11 explains.
What changed recently
Nothing changed in the language for binary search or greedy choices. Both are decades old, and ECMAScript still has no sorted collection or binary search.
ES2023 added a few array methods this module uses or mentions, as TC39’s list of finished proposals records:
findLastandfindLastIndex, which scan from the endtoSorted, which sorts a copytoSpliced, which removes items from a copy
In V8, Maglev shipped in Chrome 117 in 2023, as the V8 blog says. On Node.js 26, it’s the tier where the findIndex scan above stayed.
Cheat sheet
Figure 9 maps each sign in a problem to the pattern that fits it. In the cost column, c is the cost of one check and r the size of the range.
sign in the problem pattern cost
"first at or after", sorted lower bound O(log n)
"how many from a to b", sorted two bounds O(log n)
"smallest x such that", more is safe search on the answer O(c log r)
"most that fit in one room" greedy, earliest end O(n log n)
"merge", "free time", "busy time" sort by start, one pass O(n log n)
"how many at once", "rooms needed" sort by start, min-heap O(n log n)
lookups by exact key Map (Module 3) O(1)
Figure 9: binary search needs order, either sorted data or a monotone check, and a greedy rule needs a proof, or at least a search that failed to break it.
- Bounds: lower bound is the first
a[i] >= t, upper bound the firsta[i] > t, on[0, a.length)in O(log n); their difference counts a range. - Middle:
lo + Math.floor((hi - lo) / 2), never>>> 1on values that can pass 2³². - On the answer: a monotone yes-or-no check over a range of values;
hi = midwhen it passes,lo = mid + 1when not. - Greedy: sort, take what fits, never undo; break the rule with a brute force on small random inputs, then prove it by exchange.
- Intervals: sort by end to keep the most, by start to merge or count rooms, and decide first whether touching intervals overlap.
Next, Module 10 handles problems where no greedy rule is safe: it tries choices, explores them and undoes them, with backtracking.
Sources
- Joshua Bloch, “Extra, Extra – Read All About It: Nearly All Binary Searches and Mergesorts are Broken”, Google Research blog, June 2, 2006.
- Kevin Wayne, lecture slides for Jon Kleinberg and Éva Tardos, Algorithm Design, chapter 4, Greedy Algorithms I (interval scheduling, the exchange argument, interval partitioning, coin changing).
- ECMA-262, 2025 (Number.MAX_SAFE_INTEGER, array lengths below 2³², ToUint32 in
>>>), the current draft, TC39 proposals and finished proposals, read November 2026. - V8 source in Node.js v26.13.1:
deps/v8/include/v8-internal.h(SmiTagging<4>andSmiTagging<8>). - V8 blog: Pointer compression in V8 (2020), Maglev, V8’s fastest optimizing JIT (2023), Elements kinds in V8 (2017).