Here is a first answer to 295. Find Median from Data Stream: keep every value in an array, and sort the array each time someone asks for the median.
// The middle value of a sorted array, or the mean of the two middle values.
function middleOf(sorted: number[]): number {
const mid = sorted.length >> 1;
return sorted.length % 2 === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
}
// addNum O(1), findMedian O(n log n): sorts every value on each query. O(n) memory.
// In V8 a re-sort costs about O(n): TimSort finds the part the last query sorted as one run.
export class MedianFinderSortOnQuery {
private values: number[] = [];
addNum(num: number): void {
this.values.push(num);
}
findMedian(): number {
this.values.sort((a, b) => a - b);
return middleOf(this.values);
}
}
LeetCode allows 5 × 10⁴ calls. With a query after every add, that’s 25,000 sorts of up to 25,000 values. Even though each sort finds most of the array already in order, that’s about 3 × 10⁸ comparisons, three times the budget from Module 1, and it took 3,029.92 ms in the measurement at the end of this page. Two heaps took 9.17 ms.
This module works seven problems in two groups. The first four keep only the items that matter in a heap: the k largest, the k closest, or the two halves around a median. The last three sort a list of intervals by one end and walk it once. Each one follows the nine steps from Module 1.
After this module, you can:
- keep the k largest or k closest items in a heap of size k in O(n log k), and say when a plain sort is the better answer
- keep a running median in two heaps, and say why a sorted array still passes at this problem’s limit
- replace a step-by-step simulation with a heap, and then with a formula, when the answer follows from a few counts
- merge, insert and remove intervals after sorting by the right end, and decide first whether touching intervals overlap
- decide whether to write the heap or use the priority queue LeetCode’s editor includes
The code for this module is in module-08/ of the course repository, and node --test "module-08/**/*.test.ts" from its root runs every test. atlimit.ts in the module folder calls each solution once at its problem’s limit, so its times are rough, and yours will differ. Every number on this page comes from Node.js 24.22.1 on an Apple M2 laptop with macOS.
The patterns: keep the top in a heap, sort intervals by one end
A heap is a tree stored in an array, where every parent comes out before its children. In a min-heap the smallest item is on top; in a max-heap the largest is. Reading the top is O(1), and adding an item or removing the top is O(log n), because the item climbs or sinks along one path of the tree. Module 6 used a min-heap to merge k sorted lists, and DSA Module 8 builds it and shows how push and pop keep it in order.
Figure 1 shows a min-heap after 7, −2, 9 and 4 were pushed, in this order.
array [-2] [ 4] [ 9] [ 7]
index 0 1 2 3
tree [-2] parent of i: (i - 1) >> 1
/ \ children of i: 2i + 1 and 2i + 2
[4] [9]
/
[7]
Figure 1: a parent is never larger than its children, so the smallest item is at index 0, but the rest of the array is not sorted.
A heap is the usual way to build a priority queue, a collection where you add items in any order and take out the highest-priority one next. JavaScript has neither, so the lab uses Heap from shared/heap.ts, the one DSA Module 8 writes. You need only its public part:
// excerpt: the methods of Heap in lab/shared/heap.ts that this module uses
declare class Heap<T> {
// before(a, b) is true when a must come out before b: (a, b) => a < b is a min-heap, (a, b) => a > b a max-heap.
// Builds the heap from items in O(n), in place.
constructor(before: (a: T, b: T) => boolean, items?: T[]);
get size(): number;
peek(): T | undefined; // O(1): the top, without removing it
push(item: T): void; // O(log n)
pop(): T | undefined; // O(log n): removes and returns the top
}
To paste a heap solution into LeetCode, paste the Heap class from heap.ts with it, about 60 lines. LeetCode’s help page on its environments (updated 20 November 2026) also lists @datastructures-js/priority-queue 6.3.5 among the packages its JavaScript and TypeScript editors include.
The package gives MinPriorityQueue and MaxPriorityQueue, which take an optional (item) => number, and PriorityQueue, which takes a comparator that returns a number, as sort‘s does. Its size() is a method, where our size is a getter. We haven’t run it in LeetCode’s editor.
In an interview, ask before you rely on that package, when you state your plan and before you write code that depends on it. The interviewer decides whether a library counts, and an editor that isn’t LeetCode’s may not have it. If the answer is no, write the heap: push, pop and the two loops that move an item up or down.
Signs that point to a heap:
- “the k largest”, “the k smallest”, “the k closest”
- values that arrive one at a time, with a question about them at any time
- “the next one to run” among items whose order keeps changing
The cost is that only the top is cheap. Finding or removing any other item is O(n), and when you need every item in order anyway, a sort is simpler.
The second group works on intervals. An interval [start, end] stands for every point from start to end. In a closed interval both ends belong to it, so [1, 4] and [4, 5] share the point 4 and overlap.
Problems 56 and 57 use closed intervals; 435 says that intervals which only touch don’t overlap. DSA Module 9 merges intervals and keeps the most meetings in one room.
Signs that point to sorting intervals:
- the input is a list of
[start, end]pairs: meetings, bookings, ranges - “merge”, “insert”, “overlap”, “the fewest to remove”, “the most that fit”
Sort by start to merge or insert, and by end to keep the most. The sort is O(n log n), and it’s usually the whole cost.
Rule: When only the top few items matter, keep them in a heap. When the input is intervals, sort by one end and walk the list once.
215. Kth Largest Element in an Array
215. Kth Largest Element in an Array is rated Medium. You get an array of integers and a number k. Return the value that would sit at position k if the array were sorted from largest to smallest. Equal values each take their own position.
1 ≤ k ≤ nums.length ≤ 10^5-10^4 ≤ nums[i] ≤ 10^4- the page asks whether you can solve it without sorting
The signature is function findKthLargest(nums: number[], k: number): number. Try it on LeetCode first.
Hint
You need the k largest values, and of those only the smallest. Which kind of heap has that one on top?
Interviewer: Find the k-th largest value in this array.
Candidate: So if I sorted it from largest to smallest, I’d return the value at position k, counting from 1. Do equal values count separately?
Interviewer: Yes. It’s by position, not among distinct values.
Candidate: Is k always between 1 and the length?
Interviewer: Yes.
Candidate: How large can the array be, and may I change it?
Interviewer: Up to 10⁵ values, from −10⁴ to 10⁴. Leave it unchanged.
The interviewer and the candidate are invented. The problems, limits and timings are real.
Candidate: Here’s my example and three edge cases.
nums k expected
[7, -2, 9, 4, 9, 1] 3 7 sorted down: 9, 9, 7, 4, 1, -2
[42] 1 42 one value
[5, 5, 5, 5] 3 5 equal values each take a place
[3, -1, 8, 0] 4 -1 k = n is the smallest
Candidate: The naive answer sorts a copy from largest to smallest and reads index k − 1.
// O(n log n) time, O(n) memory: sorts a copy from largest to smallest and reads index k - 1.
export function findKthLargestSort(nums: number[], k: number): number {
return [...nums].sort((a, b) => b - a)[k - 1];
}
Candidate: That’s O(n log n) time for the sort, and O(n) memory for the copy. At 10⁵ values, n log n is about 1.7 × 10⁶ steps, far inside the budget.
So the sort fits LeetCode’s limits. In atlimit.ts it took 15.6 ms on 10⁵ random values. It’s a good first answer here: one line, and hard to get wrong.
Interviewer: The problem asks for a way without sorting. What does the sort do that you don’t need?
Candidate: It puts all n values in order, but I only need the k largest, and of those only the smallest. If I keep the k largest values seen so far, the answer is the smallest of them at the end.
Pause and predict. To keep the k largest values, should the Candidate use a min-heap or a max-heap?
Candidate: A min-heap of size k. I push each value, and when the heap holds k + 1, I pop the top. The value to throw away is the smallest of the k + 1, and a min-heap has it on top.
// O(n log k) time, O(k) memory: a min-heap keeps the k largest values seen so far;
// its top is the smallest of them, which is the k-th largest.
function findKthLargest(nums: number[], k: number): number {
const heap = new Heap<number>((a, b) => a < b);
for (const value of nums) {
heap.push(value);
if (heap.size > k) heap.pop();
}
return heap.peek()!;
}
export { findKthLargest };
The lab file imports Heap from shared/heap.ts. To paste the solution into LeetCode, drop the import line and paste the Heap class with it.
Interviewer: Trace your example.
Figure 2 traces it with k = 3. The heap columns list its values from small to large; the array inside keeps them in heap order, as in Figure 1.
value heap after push size > 3? pop heap after
7 7 no 7
-2 -2 7 no -2 7
9 -2 7 9 no -2 7 9
4 -2 4 7 9 yes -2 4 7 9
9 4 7 9 9 yes 4 7 9 9
1 1 7 9 9 yes 1 7 9 9
peek: 7
Figure 2: the heap always holds the 3 largest values so far, smallest on top, so the top at the end is the 3rd largest.
Candidate: The last value, 1, enters the heap and leaves it at once, because it’s the smallest of four. For [5, 5, 5, 5] with k = 3, every pop removes a 5 and three 5s stay, so the top is 5.
Interviewer: Final cost?
Candidate: O(n log k) time: n pushes and up to n pops, each on a heap of at most k + 1 values. O(k) memory for the heap.
In atlimit.ts, the heap took 3.4 ms at k = 10 and 8.4 ms at k = 50,000, against 15.6 ms and 15.8 ms for the sort. By Big O, the heap has no edge when k is close to n, because log k is then close to log n. It wins clearly when k is small.
Interviewer: The values only range from −10⁴ to 10⁴. Can you use that?
The Candidate’s answer
Candidate: Yes. There are only 20,001 possible values, so I count each one, then walk the counts from the largest value down until I’ve passed k values.
Counting sort orders small integers by counting each value and reading the counts in order (NIST DADS). Module 1’s bucket sort used the same idea on counts.
// O(n + R) time, O(R) memory, R = 20,001 possible values: counts each value, then walks
// the counts from the largest value down. Works only because the limits bound the values.
export function findKthLargestCounting(nums: number[], k: number): number {
const lowest = -10_000;
const counts = new Array<number>(20_001).fill(0);
for (const value of nums) counts[value - lowest]++;
let remaining = k;
for (let i = counts.length - 1; i >= 0; i--) {
remaining -= counts[i];
if (remaining <= 0) return i + lowest;
}
throw new RangeError("k is larger than nums.length");
}
Candidate: It’s O(n + R) time and O(R) memory, where R is the number of possible values. It took 1.3 ms in atlimit.ts. If the values could be any 32-bit integer, R would be 4 × 10⁹, and I’d go back to the heap.
Interviewer: Now the values arrive one at a time, and I may ask for the k-th largest after any of them.
The Candidate’s answer
Candidate: The heap already works that way. Each new value costs one push and maybe one pop, O(log k), and the top is the answer at any moment. A sort would have to run again after every value.
That’s LeetCode’s 703. Kth Largest Element in a Stream, which this course doesn’t cover. This version isn’t in the lab.
Interviewer: Without using the value range, can you get O(n) on average?
The Candidate’s answer (stretch)
Candidate: Yes, with quickselect. I pick a random pivot and split the values into larger, equal and smaller. Only the part that holds rank k matters, so I keep that part and repeat.
Quickselect is the selection method C. A. R. Hoare published as “Find” in 1961 (NIST DADS, “Find”). DSA Module 8 compares it with the heap.
// O(n) expected time (O(n^2) worst case, every pivot unlucky), O(n) memory: quickselect, random pivot.
// Split into larger, equal and smaller than the pivot; keep only the part that holds the answer.
// The equal part makes an array of one repeated value finish in one pass.
export function findKthLargestQuickselect(nums: number[], k: number): number {
let values = nums;
let rank = k; // we want the rank-th largest of `values`
while (true) {
const pivot = values[Math.floor(Math.random() * values.length)];
const larger: number[] = [];
const smaller: number[] = [];
let equal = 0;
for (const value of values) {
if (value > pivot) larger.push(value);
else if (value < pivot) smaller.push(value);
else equal++;
}
if (rank <= larger.length) {
values = larger;
} else if (rank <= larger.length + equal) {
return pivot;
} else {
rank -= larger.length + equal;
values = smaller;
}
}
}
Candidate: On average each pass keeps a constant fraction of the values, so the passes add up to about n + n/2 + n/4 and so on, which is O(n). If every pivot lands at an end, it’s O(n²). It took 5.3 ms in atlimit.ts.
The equal part matters. A version that puts values equal to the pivot on one side removes only the pivot on each pass when every value is the same. In mistakes.ts, that version took 114.9 ms on 10,000 equal values, 504.2 ms on 20,000 and 2,665.1 ms on 40,000. That’s 4.4 and 5.3 times per doubling, the O(n²) case.
One mistake is common here. mistakes.ts in the module folder prints the wrong output of every mistake in this module that has one.
- A max-heap of size k. It throws away the largest value each time, so it keeps the k smallest, and its top is the k-th smallest. Our example returns 4 instead of 7. Use a min-heap: the top must be the value you’d throw away.
Lab folder: module-08/0215-kth-largest-element-in-an-array/ in the course repository.
973. K Closest Points to Origin
973. K Closest Points to Origin is rated Medium. You get points on a plane as [x, y] pairs, and a number k. Return the k points nearest to (0, 0) by straight-line distance, in any order.
1 ≤ k ≤ points.length ≤ 10^4-10^4 ≤ x, y ≤ 10^4- the answer is unique apart from its order
The signature is function kClosest(points: number[][], k: number): number[][]. Try it on LeetCode first.
Hint
This is 215 turned around: you keep the k smallest distances. Which point should leave first when a closer one arrives?
Interviewer: Return the k points closest to the origin.
Candidate: In any order?
Interviewer: Yes.
Candidate: What if two points tie at the k-th distance, and only one fits?
Interviewer: That doesn’t happen. The answer is unique apart from its order.
Candidate: How many points?
Interviewer: Up to 10⁴, with coordinates from −10⁴ to 10⁴.
Candidate: Then x² + y² is at most 2 × 10⁸, far below 2⁵³, so the squares are exact in a JavaScript number. And I can compare squared distances: they’re in the same order as the distances, with no square root.
Candidate: Here’s my example and three edge cases.
points k expected (any order)
[[3,4],[1,-1],[-2,2],[5,5],[0,1]] 3 [[0,1],[1,-1],[-2,2]] d²: 25 2 8 50 1
[[7,7]] 1 [[7,7]] one point
[[2,0],[0,2],[9,9]] 2 [[2,0],[0,2]] a tie inside k
[[1,2],[3,4],[0,0]] 3 every point k = n
Candidate: The naive answer sorts a copy by squared distance and keeps the first k.
// The squared distance orders points the same way as the distance, with no square root.
const squared = (point: number[]) => point[0] * point[0] + point[1] * point[1];
// O(n log n) time, O(n) memory: sorts a copy by distance and keeps the first k.
export function kClosestSort(points: number[][], k: number): number[][] {
return [...points].sort((a, b) => squared(a) - squared(b)).slice(0, k);
}
Candidate: O(n log n) time and O(n) memory. At 10⁴ points that’s about 1.4 × 10⁵ steps, so it fits easily.
It took 2.0 ms in atlimit.ts. At these limits, the sort is a fine answer.
Interviewer: Say the points come from a sensor, millions of them, and you can’t keep them all.
Candidate: Then I can’t sort, but I don’t need to. I only need the k closest so far, and the one that leaves next is the farthest of them. That’s a max-heap of size k, by squared distance.
// O(n log k) time, O(k) memory: a max-heap keeps the k closest points seen so far;
// its top is the farthest of them, the first to go when a closer point arrives.
function kClosest(points: number[][], k: number): number[][] {
const heap = new Heap<number[]>((a, b) => squared(a) > squared(b));
for (const point of points) {
heap.push(point);
if (heap.size > k) heap.pop();
}
const result: number[][] = [];
while (heap.size > 0) result.push(heap.pop()!);
return result;
}
export { kClosest };
To paste it into LeetCode, paste squared and the Heap class with it.
Interviewer: Trace your example.
Figure 3 traces it with k = 3. The heap column lists squared distances from far to near, so the top comes first.
point d² heap after push size > 3? pop
[3,4] 25 25 no
[1,-1] 2 25 2 no
[-2,2] 8 25 8 2 no
[5,5] 50 50 25 8 2 yes [5,5]
[0,1] 1 25 8 2 1 yes [3,4]
left: 8 2 1 -> [-2,2] [1,-1] [0,1]
Figure 3: the max-heap keeps the 3 nearest points so far, with the farthest of them on top, ready to leave when a nearer point arrives.
Candidate: The pops at the end empty the heap from far to near, so I return [[-2,2],[1,-1],[0,1]], which is fine in any order. For [[7,7]] with k = 1, nothing is ever popped in the loop.
Interviewer: Final cost?
Candidate: O(n log k) time: n pushes and up to n pops on a heap of at most k + 1 points. O(k) memory, so a stream of millions of points needs room for only k + 1 of them.
In atlimit.ts at k = 10, the sort took 2.0 ms and the heap 1.6 ms. At 10⁴ points the difference is small. The heap’s advantage is memory, and that it works on a stream.
Interviewer: What if k is close to n?
The Candidate’s answer
Candidate: Then the heap holds almost every point, and log k is close to log n, so it’s no better than the sort. I’d sort.
Interviewer: And the distance to a point other than the origin?
The Candidate’s answer
Candidate: I subtract that point’s coordinates first: (x - px)² + (y - py)². Nothing else changes.
This version isn’t in the lab.
Interviewer: Can you get O(n) on average?
The Candidate’s answer (stretch)
Candidate: Quickselect, as in 215, on the squared distance. I split the candidates into closer, equal and farther than a random pivot. If the closer part holds at least the k I still need, I keep only it. Otherwise I take it, plus as many equal points as I need, and go on with the farther part.
// O(n) expected time (O(n^2) worst case), O(n) memory: quickselect on the squared distance.
// Keeps every point closer than the pivot, then as many pivot-distance points as k still needs.
export function kClosestQuickselect(points: number[][], k: number): number[][] {
const result: number[][] = [];
let candidates = points;
let need = k;
while (need > 0) {
const pivot = squared(candidates[Math.floor(Math.random() * candidates.length)]);
const closer: number[][] = [];
const equal: number[][] = [];
const farther: number[][] = [];
for (const point of candidates) {
const d = squared(point);
if (d < pivot) closer.push(point);
else if (d === pivot) equal.push(point);
else farther.push(point);
}
if (need <= closer.length) {
candidates = closer;
} else {
result.push(...closer, ...equal.slice(0, need - closer.length));
need -= closer.length + Math.min(equal.length, need - closer.length);
candidates = farther;
}
}
return result;
}
Candidate: It’s O(n) expected and O(n²) in the worst case, with O(n) memory for the parts. It took 2.0 ms in atlimit.ts, so at this size it buys nothing over the sort.
One mistake is common here:
- Ranking by
|x| + |y|. That’s the distance along a grid, not the straight-line distance.[[3,0],[2,2]]with k = 1 returns[[3,0]]instead of[[2,2]]: 3 + 0 is less than 2 + 2, but 8 is less than 9. Rank byx² + y².
Lab folder: module-08/0973-k-closest-points-to-origin/ in the course repository.
295. Find Median from Data Stream
295. Find Median from Data Stream is rated Hard. Build a class that receives integers one at a time and, whenever asked, returns the median of all the values so far. The median is the middle value in sorted order, or the mean of the two middle values when the count is even.
-10^5 ≤ num ≤ 10^5- at least one value is added before the first
findMedian - at most
5 × 10^4calls toaddNumandfindMediantogether - answers within
10^-5of the true median are accepted - the page asks two follow-ups: every value is in
[0, 100]; 99% of values are in[0, 100]
LeetCode’s TypeScript template is a class MedianFinder with a constructor, addNum(num: number): void and findMedian(): number. Try it on LeetCode first.
Hint
The median only needs the border between the smaller half and the larger half. What gives you the largest value of one half and the smallest of the other?
Interviewer: Build a class that returns the median of every value added so far.
Candidate: Can findMedian come before any value is added?
Interviewer: No.
Candidate: With an even count, I return the mean of the two middle values, so the answer can end in .5. How many calls, and in what mix?
Interviewer: Up to 5 × 10⁴ calls in all, in any mix.
Candidate: Then the worst case for a slow findMedian is a query after every add. And the values?
Interviewer: From −10⁵ to 10⁵.
Candidate: Here’s my example and three edge cases.
calls median after each add
add 5, 15, 1, 3, 8 5, 10, 5, 4, 5
add 7 7 one value
add 1, 4 1, 2.5 even count, odd sum
add 9, 8, 7, 10, 11 9, 8.5, 8, 8.5, 9 falling, then rising
Candidate: The naive answer keeps every value in an array and sorts it on each query.
The Candidate writes MedianFinderSortOnQuery, the class at the top of this page.
Candidate: addNum is O(1). findMedian sorts, O(n log n). With a query after every add, that’s 25,000 sorts, so O(n² log n) in all.
That’s the cost by Big O. In V8, sort is TimSort, which Module 2 defined: it finds runs that are already in order and merges them. After the first query, the array is sorted except for the new value at the end. So each later sort finds one long run and costs about n comparisons (V8 blog, “Getting things sorted in V8”). A probe counted 1.00n comparisons for a sorted array plus one value, against 12.3n to 14.3n for a random array of 12,500 to 50,000 values.
So the real cost is O(n) per query and O(n²) in all, about 3 × 10⁸ comparisons at the limit. That’s over the budget, and it took 3,029.92 ms in the measurement below.
Interviewer: What does it repeat?
Candidate: Each sort orders every value again, though only one value is new. I could keep the array sorted instead. Binary search from Module 5 finds where the new value goes, and splice puts it there.
// addNum O(n), findMedian O(1), O(n) memory: binary search finds the place (O(log n)),
// but splice shifts every later value one step to make room (O(n)).
export class MedianFinderSortedInsert {
private sorted: number[] = [];
addNum(num: number): void {
let lo = 0;
let hi = this.sorted.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (this.sorted[mid] < num) lo = mid + 1;
else hi = mid;
}
this.sorted.splice(lo, 0, num);
}
findMedian(): number {
return middleOf(this.sorted);
}
}
Candidate: The search is Module 5’s lower bound. findMedian is O(1) now. But addNum is O(n), because splice shifts every later value one place, so it’s still O(n²) in all.
By Big O it’s no better than the opening. But the shift is one move of a block of memory, and the measurement below gave 21.73 ms at the limit. So this version passes too.
Interviewer: And at 10⁶ calls?
Candidate: The shift grows with n, so the total grows four times per doubling. I want both methods in O(log n) or better. The median needs only the border between the two halves: the largest value of the smaller half and the smallest of the larger half.
Candidate: So I keep two heaps. low is a max-heap with the smaller half, and high is a min-heap with the larger half. low holds as many values as high, or one more, so the median is on the tops.
// addNum O(log n), findMedian O(1), O(n) memory: two heaps split the values in half.
// `low` is a max-heap of the smaller half, `high` a min-heap of the larger half;
// low holds as many values as high, or one more, so the median sits on the tops.
class MedianFinder {
private low = new Heap<number>((a, b) => a > b);
private high = new Heap<number>((a, b) => a < b);
constructor() {}
addNum(num: number): void {
// Pass the value through low so the largest of the smaller half moves to high.
this.low.push(num);
this.high.push(this.low.pop()!);
if (this.high.size > this.low.size) this.low.push(this.high.pop()!);
}
findMedian(): number {
if (this.low.size > this.high.size) return this.low.peek()!;
return (this.low.peek()! + this.high.peek()!) / 2;
}
}
export { MedianFinder };
Candidate: Every value goes into low first, and low‘s largest moves to high. So whatever arrives, high gets a value no smaller than anything left in low. Then, if high holds more, its smallest moves back.
To paste it into LeetCode, paste the Heap class with it.
Interviewer: Trace your example.
Figure 4 traces the five adds. low lists its values from large to small and high from small to large, so each list starts with its top.
add moves low (max) high (min) median
5 5 into low, to high, back 5 - 5
15 15 into low, 15 to high 5 15 (5 + 15) / 2 = 10
1 1 into low, 5 to high, 5 back 5 1 15 5
3 3 into low, 5 to high 3 1 5 15 (3 + 5) / 2 = 4
8 8 into low, 8 to high, 5 back 5 3 1 8 15 5
Figure 4: after every add, each value in low is at most each value in high, and low holds the extra one, so the median is on the tops.
Candidate: For a single value, it goes into low, out to high, and back, and findMedian returns it. For 1, 4, the second add leaves 1 in low and 4 in high, and the mean is 2.5.
Interviewer: Final cost?
Candidate: addNum is O(log n): at most three pushes and two pops. findMedian is O(1): it reads two tops. O(n) memory for the two heaps.
Interviewer: If every value is in [0, 100], what would you do?
The Candidate’s answer
Candidate: I keep 101 counters, as in 215’s first follow-up. addNum adds one to a counter. findMedian walks the counters to the middle position, at most 101 steps, so O(1).
// Follow-up, every value in [0, 100]: addNum O(1), findMedian O(101), O(101) memory.
// Count each value, then walk the counts to the middle position(s).
export class MedianFinderCounts {
private counts = new Array<number>(101).fill(0);
private total = 0;
addNum(num: number): void {
this.counts[num]++;
this.total++;
}
// The value at 0-based position `index` of the sorted values.
private valueAt(index: number): number {
let seen = 0;
for (let value = 0; value <= 100; value++) {
seen += this.counts[value];
if (seen > index) return value;
}
throw new RangeError("index out of range");
}
findMedian(): number {
const mid = this.total >> 1;
if (this.total % 2 === 1) return this.valueAt(mid);
return (this.valueAt(mid - 1) + this.valueAt(mid)) / 2;
}
}
Interviewer: And if only 99% of the values are in [0, 100]?
The Candidate’s answer
Candidate: I keep the 101 counters, plus a count of the values below 0 and a sorted list of the values outside the range. If fewer than half the values are below 0, and fewer than half are above 100, the middle position falls inside the counters. Then I walk them as before, starting from the count below 0.
Candidate: With 99% inside, that’s almost always the case. When it isn’t, the median is among the few values outside, and I read it from their list.
This version isn’t in the lab.
Interviewer: What if I also ask you to remove the oldest value, so you keep the median of the last w values?
The Candidate’s answer (stretch)
Candidate: A heap can’t remove a value from the middle cheaply. I’d mark the removed value and throw it away only when it reaches a top, which is called lazy deletion. A balanced search tree, which JavaScript doesn’t have, would also do it.
That’s LeetCode’s 480. Sliding Window Median, which this course doesn’t cover. This version isn’t in the lab.
Two mistakes are common here:
- Balancing the sizes without moving values across. Pushing into
lowandhighin turn keeps the sizes right, but not the order. Add 10, 1 and 2, and it returns 10 instead of 2, becauselowholds 10 whilehighholds 1. Pass every value through one heap into the other before you balance. - Integer division in the even case.
Math.floor((a + b) / 2)returns 2 instead of 2.5 for1, 4. Return(a + b) / 2.
Lab folder: module-08/0295-find-median-from-data-stream/ in the course repository.
621. Task Scheduler
621. Task Scheduler is rated Medium. A processor runs one task per time step, or stays idle. Each task has a label, a capital letter, and two runs of the same label need at least n other steps between them. Return the fewest steps that run every task.
1 ≤ tasks.length ≤ 10^4(m below)- each task is an uppercase letter
AtoZ 0 ≤ n ≤ 100
The signature is function leastInterval(tasks: string[], n: number): number. Try it on LeetCode first.
Hint
The label that appears most often decides the shape of the schedule. How many steps do its runs need, with n steps after each?
Interviewer: Return the fewest steps that run all these tasks.
Candidate: May I run the tasks in any order?
Interviewer: Yes.
Candidate: Must the gap between two runs of a label be exactly n, or at least n?
Interviewer: At least n.
Candidate: If n is 0, nothing ever waits, so the answer is the number of tasks. Do idle steps after the last task count?
Interviewer: No. The schedule ends with the last task.
Candidate: Here’s my example and three edge cases. An underscore is an idle step.
tasks n expected
AAAABC 2 10 A B C A _ _ A _ _ A
A 5 1 one task
ABCDEFAB 1 8 enough labels to fill every gap
AAABBBCCC 2 9 three labels tie for the most runs
Candidate: The naive answer simulates one step at a time. At each step I run the ready label with the most runs left, or stay idle if none is ready.
Running the label with the most left first keeps it from piling up at the end, where only idle steps could separate its runs. That’s a greedy algorithm: it takes the choice that looks best right now and never undoes it. DSA Module 9 teaches greedy choices. The lab’s tests check every solution here against a search over every possible schedule, on 300 random small inputs.
function countLabels(tasks: string[]): number[] {
const counts = new Array<number>(26).fill(0);
for (const task of tasks) counts[task.charCodeAt(0) - 65]++;
return counts;
}
// O(T * 26) time, O(26) memory: one tick at a time; each tick scans all 26 labels and runs
// the ready one with the most left (or idles when none is ready).
export function leastIntervalSimulate(tasks: string[], n: number): number {
const left = countLabels(tasks);
const readyAt = new Array<number>(26).fill(0); // first tick each label may run again
let remaining = tasks.length;
let time = 0;
while (remaining > 0) {
let best = -1;
for (let label = 0; label < 26; label++) {
if (left[label] > 0 && readyAt[label] <= time && (best === -1 || left[label] > left[best])) best = label;
}
if (best !== -1) {
left[best]--;
remaining--;
readyAt[best] = time + n + 1;
}
time++;
}
return time;
}
Candidate: Each step scans 26 labels, so it’s O(T × 26) time, where T is the answer, and O(26) memory. T is largest when every task has the same label: m(n + 1), about 10⁶ steps. So at most 2.6 × 10⁷ steps, inside the budget.
So the simulation fits. In atlimit.ts, 10⁴ A’s with n = 100 took 26.5 ms, for an answer of 1,009,900 steps.
Interviewer: What does it repeat?
Candidate: Two things. Every step scans all 26 labels to find the ready one with the most left. And it walks the idle steps one by one, about 10⁶ of them in that case.
Candidate: The scan is what a max-heap of counts replaces. A label that has run waits in a queue, with the step at which it’s ready again. Labels leave the queue in the same order they joined, because each one waits the same n steps.
The lab’s queue is Deque from shared/deque.ts, a ring buffer that DSA Module 5 writes. Its public part:
// excerpt: the methods of Deque in lab/shared/deque.ts that this module uses
declare class Deque<T> {
get size(): number;
push(item: T): void; // O(1) amortized: adds at the back
shift(): T | undefined; // O(1): removes from the front
peekFront(): T | undefined; // O(1)
}
// O(T log 26) time, O(26) memory: a max-heap of counts holds the ready labels; a label that
// just ran waits in a queue with the tick it is ready again, then goes back into the heap.
export function leastIntervalHeap(tasks: string[], n: number): number {
const ready = new Heap<number>((a, b) => a > b);
for (const count of countLabels(tasks)) if (count > 0) ready.push(count);
const cooling = new Deque<[number, number]>(); // [count left, tick it is ready]
let time = 0;
while (ready.size > 0 || cooling.size > 0) {
if (cooling.size > 0 && cooling.peekFront()![1] <= time) ready.push(cooling.shift()![0]);
if (ready.size > 0) {
const left = ready.pop()! - 1;
if (left > 0) cooling.push([left, time + n + 1]);
}
time++;
}
return time;
}
Candidate: The heap only needs counts, not labels, because the answer doesn’t say which label ran. It’s O(T log 26) time and O(26) memory. It still walks every idle step.
It took 8.1 ms in atlimit.ts. The idle steps are left, and their number follows from two counts.
Candidate: Let f be the most runs of any label, and c the number of labels with f runs. In my example, A has f = 4 runs. Its runs make f − 1 rows of n + 1 steps, each starting with A, and then a last row with every label that has f runs.
Figure 5 shows those rows for AAAABC with n = 2.
row 1 A B C a row is n + 1 = 3 steps
row 2 A _ _
row 3 A _ _
row 4 A last row: only the c labels with f runs
(f - 1)(n + 1) + c = 3 * 3 + 1 = 10 steps
Figure 5: the label with the most runs fixes the rows, and the other tasks fill gaps in them, so the length depends only on f, n and c.
Candidate: Every other task fits in a gap, at most one per row, so it never breaks the gap of n. If the other tasks overflow the gaps, I make the rows longer, and then no step is idle at all. So the answer is the larger of m and (f − 1)(n + 1) + c.
Pause and predict. For ABCDEFAB with n = 1, what does (f − 1)(n + 1) + c give, and what’s the answer?
Candidate: A and B have 2 runs each, so f = 2 and c = 2: 1 × 2 + 2 = 4. But there are 8 tasks, and none of them can be skipped, so the answer is 8, the larger of the two.
// O(m) time, O(26) memory: the most frequent label fixes the shape. With f runs of it, there are
// f - 1 gaps of n slots, then one final row with every label that also has f runs.
// If other tasks overflow the gaps, no idle tick is needed and the answer is m.
function leastInterval(tasks: string[], n: number): number {
const counts = countLabels(tasks);
const most = Math.max(...counts);
let labelsWithMost = 0;
for (const count of counts) if (count === most) labelsWithMost++;
return Math.max(tasks.length, (most - 1) * (n + 1) + labelsWithMost);
}
export { leastInterval };
To paste it into LeetCode, paste countLabels with it.
Interviewer: Trace your example.
Candidate: countLabels gives A = 4, B = 1, C = 1, and 0 for the rest. most is 4, and only A has 4, so labelsWithMost is 1. (4 − 1) × (2 + 1) + 1 is 10, and the larger of 6 and 10 is 10. For A with n = 5: most is 1, so the formula gives 0 × 6 + 1 = 1.
Figure 5 already shows this example’s rows, so the trace needs no new figure.
Interviewer: Final cost?
Candidate: O(m) time to count, and O(26) memory for the counts.
It took 0.1 ms in atlimit.ts on the 10⁴ A’s, against 26.5 ms for the simulation.
Interviewer: Return the schedule itself, not only its length.
The Candidate’s answer
Candidate: The formula can’t give that. I’d use the heap simulation and keep the label with each count in the heap, then record each step: the label that ran, or an idle step. That’s O(T log 26) time and O(T) memory for the schedule.
This version isn’t in the lab.
Interviewer: What if the tasks must run in the given order?
The Candidate’s answer
Candidate: Then there’s no choice left. I walk the list and keep, for each label, the first step at which it may run again, in a Map. Each task runs at that step or at the current one, whichever is later. That’s O(m) time.
That’s LeetCode’s 2365. Task Scheduler II, which this course doesn’t cover. This version isn’t in the lab.
Interviewer: And labels beyond the 26 letters?
The Candidate’s answer
Candidate: The formula needs only the counts, so I’d count in a Map instead of an array. It’s still O(m) time, and O(L) memory for L labels.
This version isn’t in the lab.
Two mistakes are common here:
- Dropping the
Math.maxwith the number of tasks. The formula alone assumes idle steps exist.ABCDEFABwith n = 1 returns 4 instead of 8. - Adding 1 for the last row instead of c. Every label tied for the most runs has a run in the last row.
AAABBBwith n = 2 returns 7 instead of 8.
Lab folder: module-08/0621-task-scheduler/ in the course repository.
56. Merge Intervals
56. Merge Intervals is rated Medium. You get a list of intervals in no particular order. Merge every group that overlaps, where sharing a single point counts, and return the separate intervals that cover the same points.
1 ≤ intervals.length ≤ 10^4- each interval is
[start, end]with0 ≤ start ≤ end ≤ 10^4
The signature is function merge(intervals: number[][]): number[][]. Try it on LeetCode first.
Hint
Sort by start. Which of the blocks built so far can the next interval overlap?
Interviewer: Merge the overlapping intervals in this list.
Candidate: Is the list sorted?
Interviewer: No.
Candidate: Do intervals that only touch merge, like [1, 4] and [4, 5]?
Interviewer: Yes. They share the point 4.
Candidate: Can an interval be one point, with start equal to end?
Interviewer: Yes.
Candidate: Does the output need an order?
Interviewer: Sorted by start is fine.
Candidate: Here’s my example and three edge cases.
intervals expected
[[9,12],[2,5],[4,7],[12,14],[20,21]] [[2,7],[9,14],[20,21]]
[[3,3]] [[3,3]] one point
[[1,10],[2,3],[4,5]] [[1,10]] nested: end can't shrink
[[1,2],[3,4]] [[1,2],[3,4]] no shared point
Candidate: The naive answer adds the intervals one at a time to a list of separate blocks. Each new interval swallows every block it overlaps.
// O(n^2) time, O(n) memory: adds the intervals one at a time to a list of separate blocks;
// each new interval swallows every block it overlaps, which means a scan of the whole list.
export function mergeOneByOne(intervals: number[][]): number[][] {
let blocks: number[][] = [];
for (const [start, end] of intervals) {
let merged = [start, end];
const kept: number[][] = [];
for (const block of blocks) {
if (block[0] <= merged[1] && merged[0] <= block[1]) {
merged = [Math.min(merged[0], block[0]), Math.max(merged[1], block[1])];
} else {
kept.push(block);
}
}
kept.push(merged);
blocks = kept;
}
return blocks.sort((a, b) => a[0] - b[0]); // same order as the fast version
}
Candidate: Two intervals overlap when each one starts at or before the other ends. A block that misses the new interval and everything it swallowed can’t touch the merged block, so the blocks stay separate. Each interval scans every block, so it’s O(n²) time and O(n) memory.
At 10⁴ intervals that’s 10⁸ steps, at the budget. In atlimit.ts, 10⁴ intervals that never merge took 270.8 ms, so it fits.
Interviewer: What does it repeat?
Candidate: Each new interval is compared with every block. If I sort by start first, every earlier block ends before the last block starts, so a new interval can only overlap the last block.
// O(n log n) time, O(n) memory: sort by start; then an interval can only overlap the last
// block, because every earlier block ends before the last block starts.
function merge(intervals: number[][]): number[][] {
const sorted = [...intervals].sort((a, b) => a[0] - b[0]);
const result: number[][] = [];
for (const [start, end] of sorted) {
const last = result[result.length - 1];
if (last !== undefined && start <= last[1]) {
last[1] = Math.max(last[1], end);
} else {
result.push([start, end]);
}
}
return result;
}
export { merge };
Candidate: I sort a copy, because sort changes the array it’s called on. And I push a new pair, so growing last never changes the caller’s intervals.
Interviewer: Trace your example.
Figure 6 traces it after the sort.
interval last block start <= last end? blocks
[2,5] - no block yet [2,5]
[4,7] [2,5] 4 <= 5: extend [2,7]
[9,12] [2,7] 9 <= 7: no [2,7] [9,12]
[12,14] [9,12] 12 <= 12: extend [2,7] [9,14]
[20,21] [9,14] 20 <= 14: no [2,7] [9,14] [20,21]
Figure 6: after sorting by start, each interval can only reach the last block, so one comparison per interval merges the list.
Candidate: [9,12] and [12,14] merge because they share 12. For [[1,10],[2,3],[4,5]], the end stays 10, because Math.max never lets it shrink.
Interviewer: Final cost?
Candidate: O(n log n) time for the sort, then O(n) for the pass. O(n) memory for the sorted copy and the result.
It took 2.6 ms in atlimit.ts, against 270.8 ms for one by one.
Interviewer: Now the intervals arrive one at a time, and you must report the merged set after each.
The Candidate’s answer
Candidate: I keep the blocks sorted and separate, and insert each new interval the way 57 does, below. That’s O(n) per interval, mostly to copy the list. A balanced search tree keyed by start would make it O(log n) per interval, but JavaScript doesn’t ship one.
This version isn’t in the lab.
Interviewer: And if there are too many intervals for memory?
The Candidate’s answer
Candidate: I sort them by start on disk, with an external sort. The pass after the sort needs only the last block, so it can stream through them and write each finished block out.
This version isn’t in the lab.
Interviewer: What if the intervals were half-open, [start, end)?
The Candidate’s answer
Candidate: Then [1, 4) and [4, 5) share no point, so I change start <= last[1] to start < last[1]. DSA Module 9’s mergeBusy merges half-open meetings that way.
Three mistakes are common here:
- Overwriting the end.
last[1] = endinstead of the larger of the two ends lets a nested interval shrink the block.[[1,10],[2,3]]returns[[1,3]]instead of[[1,10]]. - Using
<for closed intervals. Intervals that share one point stay apart.[[1,4],[4,5]]returns[[1,4],[4,5]]instead of[[1,5]]. - Forgetting to sort. The pass only checks the last block.
[[4,7],[1,2],[2,4]]returns[[4,7]]instead of[[1,7]], and it loses the other two intervals.
Lab folder: module-08/0056-merge-intervals/ in the course repository.
57. Insert Interval
57. Insert Interval is rated Medium. You get a list of intervals, sorted by start with no overlaps, and one new interval. Return the list with the new interval added, merged with every interval it overlaps, so the result is still sorted and separate.
0 ≤ intervals.length ≤ 10^40 ≤ start ≤ end ≤ 10^5for every interval and for the new one- the list is sorted by start, and its intervals don’t overlap
- sharing one point counts as overlapping
The signature is function insert(intervals: number[][], newInterval: number[]): number[][]. Try it on LeetCode first.
Hint
The list is sorted and separate, so the intervals that overlap the new one sit next to each other in the middle.
Interviewer: Insert this interval into a sorted list of separate intervals.
Candidate: The list is sorted by start, and no two of its intervals overlap?
Interviewer: Both, yes.
Candidate: Can the list be empty?
Interviewer: Yes.
Candidate: Does touching count as overlapping, as in 56?
Interviewer: Yes.
Candidate: May I return a new array?
Interviewer: Yes.
Candidate: Here’s my example and three edge cases.
intervals new expected
[[1,2],[5,7],[9,11],[14,15]] [6,9] [[1,2],[5,11],[14,15]]
[] [4,6] [[4,6]] empty list
[[3,5],[8,9]] [5,8] [[3,9]] touches both
[[3,5],[8,9]] [6,7] [[3,5],[6,7],[8,9]] fits in a gap
Candidate: The naive answer adds the new interval to the list and runs 56’s merge on it.
// O(n log n) time, O(n) memory: add the new interval and merge everything again,
// ignoring that the list was already sorted and separate.
export function insertByMerging(intervals: number[][], newInterval: number[]): number[][] {
return merge([...intervals, newInterval]);
}
Candidate: It’s O(n log n) time for the sort and O(n) memory, and it’s correct, because 56’s merge handles any list.
By Big O it ignores that the list is already sorted. In practice TimSort finds the sorted list as one run, as in 295, so the sort is close to linear. It took 0.8 ms in atlimit.ts on 10⁴ intervals, against 0.4 ms for the pass below. If time is short in an interview, it’s a fine answer to give first.
Interviewer: What does it ignore?
Candidate: It sorts a list that’s already sorted. Because the list is sorted and separate, it comes in three parts: the intervals that end before the new one starts, the ones that overlap it, and the rest. One pass handles each part in turn.
// O(n) time, O(n) memory for the result: one pass in three parts. Copy the intervals that end
// before the new one starts, absorb every interval that overlaps it, copy the rest.
function insert(intervals: number[][], newInterval: number[]): number[][] {
const result: number[][] = [];
let [start, end] = newInterval;
let i = 0;
while (i < intervals.length && intervals[i][1] < start) {
result.push(intervals[i]);
i++;
}
while (i < intervals.length && intervals[i][0] <= end) {
start = Math.min(start, intervals[i][0]);
end = Math.max(end, intervals[i][1]);
i++;
}
result.push([start, end]);
while (i < intervals.length) {
result.push(intervals[i]);
i++;
}
return result;
}
export { insert };
Candidate: In the middle loop, end grows as intervals are absorbed, so an interval that overlaps only the grown end joins too.
Interviewer: Trace your example.
Figure 7 traces it with the new interval [6,9].
interval test part start end result
[1,2] 2 < 6: ends before copy 6 9 [1,2]
[5,7] 5 <= 9: overlaps absorb 5 9 [1,2]
[9,11] 9 <= 9: overlaps absorb 5 11 [1,2]
middle run over push 5 11 [1,2] [5,11]
[14,15] 14 > 11: after it copy 5 11 [1,2] [5,11] [14,15]
Figure 7: the overlapping intervals form one run in the middle of the sorted list, so one pass copies, absorbs and copies.
Candidate: [9,11] starts at 9, which the new interval reaches, so it’s absorbed too, and the end becomes 11. For the empty list, all three loops skip, and the result is [[4,6]].
Interviewer: Final cost?
Candidate: O(n) time: each interval is looked at once. O(n) memory for the result.
Interviewer: Could binary search make it faster?
The Candidate’s answer
Candidate: Binary search could find both ends of the middle run in O(log n). But I still copy the other intervals into the result, which is O(n), so the total doesn’t change.
This version isn’t in the lab.
Interviewer: What if many intervals arrive, one after another?
The Candidate’s answer
Candidate: Inserting q of them one at a time costs O(n) each. If I don’t need the result in between, I’d collect them all and run 56’s merge once, O((n + q) log(n + q)).
This version isn’t in the lab.
Interviewer: Can you do it in place?
The Candidate’s answer
Candidate: Yes, with splice: replace the middle run with the merged interval. It’s still O(n), because splice shifts every later interval.
This version isn’t in the lab.
Two mistakes are common here:
- Adding the new interval only when a later interval is found. If the new interval reaches the end of the list, nothing adds it.
[[1,2],[3,5]]with[4,9]returns[[1,2]]instead of[[1,2],[3,9]]. Push it after the middle loop, as the three-part pass does. intervals[i][1] <= startin the first loop. That treats touching as apart, so[[1,3]]with[3,4]returns[[1,3],[3,4]]instead of[[1,4]]. This one isn’t inmistakes.ts; the output follows from the first loop copying[1,3].
Lab folder: module-08/0057-insert-interval/ in the course repository.
435. Non-overlapping Intervals
435. Non-overlapping Intervals is rated Medium. You get a list of intervals. Return the fewest you must remove so that no two of the rest overlap. Here, intervals that only touch, end to start, don’t overlap.
1 ≤ intervals.length ≤ 10^5-5 × 10^4 ≤ start < end ≤ 5 × 10^4
The signature is function eraseOverlapIntervals(intervals: number[][]): number. Try it on LeetCode first.
Hint
Removing the fewest is keeping the most. Which interval should you keep first to leave the most room for the others?
Interviewer: Remove the fewest intervals so that the rest don’t overlap.
Candidate: Do [1, 2] and [2, 3] overlap?
Interviewer: No. Here they only touch.
Candidate: That’s the opposite of 56, so an interval may start exactly where another ends. Is the list sorted?
Interviewer: No.
Candidate: How many intervals, and can values be negative?
Interviewer: Up to 10⁵, from −5 × 10⁴ to 5 × 10⁴, and every interval has a positive length.
Candidate: Then O(n²) is 10¹⁰ steps, far too slow. I’m aiming for O(n log n).
Candidate: Here’s my example and three edge cases.
intervals expected
[[1,8],[2,4],[3,5],[4,6],[7,9]] 2 keep [2,4] [4,6] [7,9]
[[5,6]] 0 one interval
[[1,2],[1,2],[1,2]] 2 k copies: remove k - 1
[[1,100],[2,3],[4,5],[6,7]] 1 remove the long one
Candidate: Removing the fewest is keeping the most. The naive answer tries every subset to keep, and checks that it has no overlap.
// O(2^n * n log n) time, O(n) memory: tries every subset to keep and checks it. Tiny inputs only.
export function eraseOverlapIntervalsBrute(intervals: number[][]): number {
const n = intervals.length;
let mostKept = 0;
for (let mask = 0; mask < 1 << n; mask++) {
const kept = intervals.filter((_, i) => mask & (1 << i)).sort((a, b) => a[0] - b[0]);
let fits = true;
for (let i = 1; i < kept.length; i++) if (kept[i][0] < kept[i - 1][1]) fits = false;
if (fits) mostKept = Math.max(mostKept, kept.length);
}
return n - mostKept;
}
Candidate: There are 2ⁿ subsets, each sorted and checked, so O(2ⁿ · n log n) time. That’s hopeless past about 20 intervals. It’s only useful to check a faster answer on small inputs.
The lab’s tests use it that way. A middle answer exists, the longest chain of intervals with dynamic programming from Module 11 (stretch). It’s O(n²), and the lab’s eraseOverlapIntervalsChains took 16,780.4 ms at 10⁵ in atlimit.ts.
Interviewer: What does the brute force ignore?
Candidate: It checks the same overlaps in subset after subset. But one choice is always safe: keep the interval that ends first. It leaves the most room for the others. Then I repeat with the intervals that start at or after its end.
Candidate: Here’s why it’s safe. Take any best set of kept intervals, and swap its first interval for the one that ends earliest overall.
Candidate: The new one ends no later, so it can’t overlap the second interval in the set. The count stays the same, and the same swap works for the rest.
That argument is an exchange argument: a best answer can be changed, one step at a time, into the greedy answer without getting worse. It’s the proof in Kevin Wayne’s slides for Kleinberg and Tardos, chapter 4, and DSA Module 9 walks through it for meetings.
// O(n log n) time, O(n) memory for the sorted copy: sort by end and keep each interval that
// starts at or after the end of the last one kept. Ending first leaves the most room for the rest.
function eraseOverlapIntervals(intervals: number[][]): number {
const sorted = [...intervals].sort((a, b) => a[1] - b[1]);
let kept = 0;
let lastEnd = -Infinity;
for (const [start, end] of sorted) {
if (start >= lastEnd) {
kept++;
lastEnd = end;
}
}
return sorted.length - kept;
}
export { eraseOverlapIntervals };
Interviewer: Trace your example.
Figure 8 traces it after the sort by end.
interval start >= lastEnd? keep? lastEnd kept
[2,4] 2 >= -Infinity keep 4 1
[3,5] 3 >= 4: no remove 4 1
[4,6] 4 >= 4 keep 6 2
[1,8] 1 >= 6: no remove 6 2
[7,9] 7 >= 6 keep 9 3
removed: 5 - 3 = 2
Figure 8: sorted by end, each kept interval is the one that frees the timeline soonest, so every later interval has the most room left.
Candidate: [4,6] is kept because it only touches [2,4]. For [[1,2],[1,2],[1,2]], the first copy is kept, and the other two start at 1, before lastEnd of 2, so 2 are removed.
Interviewer: Final cost?
Candidate: O(n log n) time for the sort, then O(n) for the pass. O(n) memory for the sorted copy.
It took 25.1 ms in atlimit.ts at 10⁵ intervals, against 16,780.4 ms for the O(n²) chain version.
Interviewer: Which intervals would you remove?
The Candidate’s answer
Candidate: The ones the loop skips. I’d push each skipped interval to a list instead of only counting. The cost doesn’t change.
This version isn’t in the lab.
Interviewer: What if each interval has a weight, and you keep the most total weight?
The Candidate’s answer (stretch)
Candidate: Then the earliest end can lose. A short interval that ends first may block one with a much larger weight. I’d use the chain version with dynamic programming, plus a binary search for the last interval that ends before each one starts. That’s weighted interval scheduling, the kind of problem Module 11 works.
This version isn’t in the lab.
Interviewer: How many rooms would you need so that nothing is removed?
The Candidate’s answer
Candidate: I sort by start and keep a min-heap of the end times of the rooms in use. For each interval, if the earliest end is at or before its start, that room is free, so I pop it. Then I push the new end. The largest heap size is the answer, in O(n log n).
That’s LeetCode’s 253, a Premium problem, and DSA Module 9’s exercise rooms-needed. This version isn’t in the lab.
Two mistakes are common here:
- Sorting by start instead of end. The interval that starts first may end last. Our example returns 4 instead of 2, because it keeps
[1,8], which overlaps all four of the others. Sort by end. start > lastEnd. That counts touching intervals as overlapping.[[1,2],[2,3]]returns 1 instead of 0. Use>=, because this problem says touching is allowed.
Lab folder: module-08/0435-non-overlapping-intervals/ in the course repository.
Measured: Find Median from Data Stream, three ways
Find Median from Data Stream, the problem at the top of this page, is the one this module measures, with bench.ts from DSA Module 1. Each run makes n calls, an addNum and then a findMedian, in turn. That’s the worst mix for a slow query. The values are random in [-10^5, 10^5], and 50,000 calls is LeetCode’s limit.
// measure.ts: Module 8's measurement. 295. Find Median from Data Stream: sort on every query,
// sorted insert, and two heaps. Each run makes n calls: addNum, then findMedian, in turn.
// Run from the repository root: node module-08/measure.ts
import { bench } from "../shared/bench.ts";
import { MedianFinderSortOnQuery, MedianFinderSortedInsert, MedianFinder } from "./0295-find-median-from-data-stream/solution.ts";
let sink = 0;
type Finder = { addNum(num: number): void; findMedian(): number };
// Values in [-10^5, 10^5] at random, as the page allows.
const randomValues = (calls: number) => Array.from({ length: calls / 2 }, () => Math.floor(Math.random() * 200_001) - 100_000);
const stream = (Finder: new () => Finder) => (values: number[]) => {
const finder = new Finder();
for (const value of values) {
finder.addNum(value);
sink += finder.findMedian();
}
};
const sizes = [12_500, 25_000, 50_000]; // 50,000 calls is the page's limit
bench("sort on every query", sizes, randomValues, stream(MedianFinderSortOnQuery));
bench("sorted insert (binary search + splice)", sizes, randomValues, stream(MedianFinderSortedInsert));
bench("two heaps", sizes, randomValues, stream(MedianFinder));
// Past the page's limit, to read the growth of the two faster ones.
bench("sorted insert, larger n", [100_000, 200_000, 400_000], randomValues, stream(MedianFinderSortedInsert));
bench("two heaps, larger n", [400_000, 800_000, 1_600_000], randomValues, stream(MedianFinder));
console.log(`\nsink ${sink}`);
bench runs each size once to warm up, then five times on fresh values, and prints the median and how many times slower each size is than the one before. Making the values isn’t timed.
Pause and predict. When the number of calls doubles, by how much should each version’s time grow? Sorting on every query re-sorts a nearly sorted array, sorted insert shifts part of an array, and two heaps climb a path of length log n.
Here is what node module-08/measure.ts printed:
sort on every query
n median ms x prev
12,500 170.70
25,000 682.48 4.0
50,000 3029.92 4.4
sorted insert (binary search + splice)
n median ms x prev
12,500 1.99
25,000 6.11 3.1
50,000 21.73 3.6
two heaps
n median ms x prev
12,500 2.23
25,000 4.33 1.9
50,000 9.17 2.1
sorted insert, larger n
n median ms x prev
100,000 90.82
200,000 370.40 4.1
400,000 1475.82 4.0
two heaps, larger n
n median ms x prev
400,000 88.48
800,000 184.90 2.1
1,600,000 388.37 2.1
sink 629873903
These numbers come from one run on an Apple M2 laptop with macOS and Node.js 24.22.1. Your numbers will differ, but the ratios should look alike.
Sorting on every query grew 4.0 and 4.4 times per doubling, the O(n²) of n re-sorts that each cost about n comparisons. At LeetCode’s limit it took 3,029.92 ms, about 330 times the 9.17 ms of two heaps.
Two heaps grew 1.9 to 2.1 times per doubling at every size, up to 1.6 million calls. That’s O(n log n) in all, with a log factor too small to see across one doubling.
Sorted insert was faster than two heaps at 12,500 calls, 1.99 ms against 2.23 ms, and 2.4 times slower at the limit. Its O(n²) shows past the limit: 4.1 and 4.0 times per doubling, and 1,475.82 ms at 400,000 calls, where two heaps took 88.48 ms. So at this problem’s limit the simpler sorted array would pass, and the heaps are the answer for the interviewer’s larger input. sink adds up the medians, so V8 can’t skip the calls.
Underneath: heaps and sorting in JavaScript
JavaScript has no heap and no priority queue. The ECMAScript draft has neither, and no TC39 proposal for one exists at any stage, as of November 2026 (ECMA-262, TC39 proposals). So in an interview you write a binary heap over a plain array. The parent of index i is at (i − 1) >> 1, and its children are at 2i + 1 and 2i + 2 (Sedgewick and Wayne, section 2.4). Or, on LeetCode, you use the package from the pattern section, once the interviewer agrees.
Node.js has a binary heap of its own, lib/internal/priority_queue.js, which orders its timers. It’s internal, so your code can’t import it (source, v26.13.1). DSA Module 8 shows how push and pop move items, measures what a heap entry costs in memory, and compares the heap with sorting and quickselect.
The interval problems lean on Array.prototype.sort instead. It has been stable since ES2019 (ECMAScript 2019). V8 has used TimSort for it since V8 7.0, which is O(n log n) in the worst case and O(n) on input that’s already sorted (V8 blog). That last fact showed twice on this page. Re-sorting the opening’s nearly sorted array cost about n comparisons, and 57’s “append and merge again” ran nearly as fast as the linear pass.
sort changes the array it’s called on, so this module’s solutions sort a copy ([...intervals]). toSorted, from ES2023, does both in one call.
Cheat sheet
Figure 9 maps each problem in this module to the sign that pointed to its solution.
sign in the problem problem the move cost
the k-th largest 215 min-heap of size k O(n log k)
the k closest 973 max-heap of size k O(n log k)
a median as values arrive 295 two heaps O(log n) add
fewest steps, labels must wait 621 count, then a formula O(m)
merge overlapping intervals 56 sort by start, extend O(n log n)
insert into a sorted list 57 copy, absorb, copy O(n)
fewest removed, none overlap 435 sort by end, greedy O(n log n)
Figure 9: a heap keeps only the top items in order, and a sort by one end puts each interval next to the only one it can affect.
- Heaps: to keep the k best, put the worst of them on top and pop it when one more arrives. A min-heap keeps the largest, a max-heap the closest, and two heaps hold the halves around a median.
- Intervals: decide first whether touching overlaps (56 and 57 yes, 435 no). Sort by start to merge or insert, by end to keep the most.
- LeetCode’s package:
@datastructures-js/priority-queue6.3.5 is listed in its editors; ask the interviewer before you use it, or pasteHeap. - When the naive answer passes: the sort in 215, 973 and 57, the simulation in 621, one by one in 56, and sorted insert in 295 all fit their limits.
- Next: Module 9 works graphs, starting from rotting oranges that rescan the whole grid every minute.
Sources
- LeetCode problem pages, checked on 2026-11-20: 215, 973, 295, 621, 56, 57, 435, and 703, 480 and 2365 for follow-ups.
- LeetCode, “What are the environments for the programming languages?”, updated 2026-11-20. The package’s API:
@datastructures-js/priority-queue6.3.5 type definitions. - Robert Sedgewick and Kevin Wayne, Algorithms, 4th edition: 2.4 Priority Queues (binary heap, push and pop in O(log n)) and 2.5 Sorting Applications (selection, linear on average).
- Dictionary of Algorithms and Data Structures, NIST: “counting sort” and “Find” (C. A. R. Hoare, “Algorithm 65: Find”, Communications of the ACM 4(7), 1961).
- Kevin Wayne, lecture slides for Kleinberg and Tardos, Algorithm Design, chapter 4 (earliest finish time first, and its exchange argument).
- V8 blog, “Getting things sorted in V8”. ECMAScript 2019 (stable
sort). Node.js source,lib/internal/priority_queue.js. - Node.js documentation: TypeScript, test runner.