Here is a first answer to 981. Time Based Key-Value Store: keep every version of a key in a list, and on each read, scan the list from the oldest version.
// set O(1) amortized; get O(k) for a key with k stored timestamps: get scans the key's timestamps
// from the oldest and keeps the last one that is <= t.
export class TimeMapScan {
entries = new Map<string, { timestamp: number; value: string }[]>();
set(key: string, value: string, timestamp: number): void {
const list = this.entries.get(key);
if (list) list.push({ timestamp, value });
else this.entries.set(key, [{ timestamp, value }]);
}
get(key: string, timestamp: number): string {
const list = this.entries.get(key);
if (!list) return "";
let answer = "";
for (const entry of list) {
if (entry.timestamp > timestamp) break;
answer = entry.value;
}
return answer;
}
}
LeetCode allows 2 × 10⁵ calls. With 10⁵ versions of one key and 10⁵ reads, the scan reads up to 10¹⁰ entries, 100 times the budget from Module 1. In one run of atlimit.ts in the module folder, it took 4,250.1 ms with random read times, and 11,602.6 ms when every read asked for the latest time. A binary search took 28.2 ms and 13.8 ms on the same calls.
This module works six problems where the data is sorted, or sorted in pieces, so one comparison rules out half of what is left. Each one follows the nine steps from Module 1, from the naive solution to the optimal one.
After this module, you can:
- write a binary search on a closed range that stops on a match, and say why the loop runs while
lo <= hi - write a binary search that shrinks to the first index where a yes-or-no question turns true, and say when to keep
mid - search data that is sorted only in pieces (a grid of chained rows, a rotated list) by working out which piece is sorted
- binary search on something that isn’t a position in the input: where to cut two sorted lists to find their median
- keep a sorted list per key by appending, and find the latest version at or before a time in O(log k)
The code for this module is in module-05/ of the course repository, and node --test "module-05/**/*.test.ts" from its root runs every test. Every number on this page comes from Node.js 24.22.1 on an Apple M2 laptop with macOS.
The pattern: binary search drops half the range per look
Binary search finds a place in sorted data by looking at the middle of the range that can still hold the answer, then dropping the half that can’t. Module 2 used it inside Two Sum II, and DSA Module 9 teaches it. Each look halves the range, so 10⁵ items need about 17 looks.
This module writes the loop in two shapes. A closed range [lo, hi] includes both ends. Its loop runs while lo <= hi and returns as soon as the middle matches. Otherwise it moves past mid (lo = mid + 1 or hi = mid - 1). It answers “is it there, and where?”
The second shape answers “where is the first yes?” A yes-or-no question about positions is monotone when it is false up to some index and true from there on, never switching back. The loop runs while lo < hi, and when mid says yes it keeps mid with hi = mid, because mid may be the first yes. When lo and hi meet, they point at it.
Signs that point to this pattern:
- the input is sorted, or sorted in a few pieces
- the page asks for O(log n), or each query must be faster than a pass over the data
- the question is “the latest at or before”, “the first that” or “the smallest that”
- a yes-or-no question about positions that switches once
The cost is that the data must already be sorted. Sorting first costs O(n log n), so for a single lookup a scan is cheaper. And inserting into the middle of a sorted array shifts every later item, which is O(n).
Rule: When a yes-or-no question about positions switches once, binary search finds the switch in O(log n) looks.
704. Binary Search
704. Binary Search is rated Easy. You get a list of distinct integers sorted from smallest to largest, and a target. Return the target’s index, or -1 if it isn’t in the list.
1 ≤ n ≤ 10^4(n =nums.length)-10^4 < nums[i], target < 10^4- all numbers are distinct, sorted ascending
- the time must be O(log n)
The signature is function search(nums: number[], target: number): number. Try it on LeetCode first.
Hint
Compare the target with the middle number. Which half can’t hold it?
Interviewer: Find this number in a sorted list, and return its index.
Candidate: The list is sorted ascending, and I return -1 if the target is missing. Can numbers repeat?
Interviewer: No, they’re all distinct.
Candidate: Then there’s at most one answer. Can the list be empty?
Interviewer: No, it has at least one number.
The interviewer and the candidate are invented. The problems, limits and timings are real.
Candidate: Here’s my example and three edge cases.
nums target expected
[2, 8, 13, 21, 34, 55, 89] 34 4
[2, 8, 13, 21, 34, 55, 89] 30 -1 falls in a gap
[5] 5 0 one number, found
[5] -5 -1 one number, missing
Candidate: The naive solution reads every number until it meets the target.
// O(n) time, O(1) memory: looks at every number until it finds target.
export function searchLinear(nums: number[], target: number): number {
for (let i = 0; i < nums.length; i++) {
if (nums[i] === target) return i;
}
return -1;
}
Candidate: That’s O(n) time and O(1) memory. At 10⁴ numbers it’s 10⁴ steps, far under the budget, so the clock allows it. But the page asks for O(log n), so this answer breaks the rule.
Interviewer: What does the scan ignore?
Candidate: The order. If the number at some index is smaller than the target, every number before it is smaller too. So one comparison answers for a whole side.
Candidate: I keep the closed range [lo, hi] that can still hold the target, and look at its middle. If the middle is smaller than the target, the target can only be right of it. If it’s larger, only left. When the range is empty, the target isn’t there.
// O(log n) time, O(1) memory: each step halves the range [lo, hi] that can still hold target.
function search(nums: number[], target: number): number {
let lo = 0;
let hi = nums.length - 1;
while (lo <= hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (nums[mid] === target) return mid;
if (nums[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
export { search };
Candidate: I write the middle as lo + Math.floor((hi - lo) / 2), in every search I write.
“Underneath”, near the end of this page, explains why the course never writes the middle as (lo + hi) >>> 1.
Pause and predict. For the target 34, which middles does search look at, and how many looks does it need?
Interviewer: Trace your example.
Figure 1 traces the search for 34. The array row has the indexes under it.
nums [2] [8] [13] [21] [34] [55] [89]
0 1 2 3 4 5 6
step lo hi mid nums[mid] then
1 0 6 3 21 21 < 34: lo = 4
2 4 6 5 55 55 > 34: hi = 4
3 4 4 4 34 found: return 4
Figure 1: each look drops the half that can’t hold 34, so seven numbers need three looks.
Candidate: The third look has lo === hi, a range of one number. That’s why the loop runs while lo <= hi: with <, it would stop before checking that number.
Candidate: For 30, the same three middles come up, but 34 is larger than 30, so hi becomes 3. Now lo is past hi, the range is empty, and I return -1.
Interviewer: Final cost?
Candidate: O(log n) time: each look at least halves the range, so 10⁴ numbers need at most 14 looks. O(1) memory: three indexes.
Interviewer: What if numbers can repeat, and I want the first index of the target?
The Candidate’s answer
Candidate: Then I don’t stop at a match. I search for the first index whose number is at least the target, with the second loop shape. That’s hi = mid when nums[mid] >= target, and lo = mid + 1 otherwise.
Candidate: A second search for the first index whose number is more than the target gives the end of the run. The difference of the two is how many times the target appears.
That’s LeetCode’s 34. Find First and Last Position of Element in Sorted Array, which this course doesn’t cover. Problem 981 below names these two searches. This version isn’t in the lab.
Interviewer: Would you write it recursively?
The Candidate’s answer
Candidate: I could. Both versions are O(log n) time, but the recursive one keeps one frame per look on the call stack, so O(log n) memory. That’s only about 14 frames here, so it’s safe. The loop needs O(1) memory and no extra function, so I’d write the loop.
Interviewer: Java code often writes the middle as (lo + hi) >>> 1. Why not here?
The Candidate’s answer
Candidate: In JavaScript, >>> first turns its left side into an unsigned 32-bit integer. So a sum of 2³² or more wraps around to a small number.
Candidate: Array indexes never get that large, but a search over a range of values can. So I keep one form that is exact for every range, lo + Math.floor((hi - lo) / 2).
Two mistakes are common here. mistakes.ts in the module folder prints the wrong output of every mistake in this module.
while (lo < hi)with a closed range. The last candidate, wherelo === hi, is never checked.[5]with target 5 returns-1instead of0. With[lo, hi], loop whilelo <= hi.lo = midinstead oflo = mid + 1. Whenhiislo + 1, the middle isloagain, and the range never shrinks. On[1, 3]with target 3, the lab version was still atlo=0 hi=1when its step cap stopped it, instead of returning1. The middle is known to be too small, so move past it.
Lab folder: module-05/0704-binary-search/ in the course repository.
74. Search a 2D Matrix
74. Search a 2D Matrix is rated Medium. You get a grid of integers in which each row is sorted, and each row’s first number is above the last number of the row before it. Return whether a target is in the grid.
1 ≤ m, n ≤ 100(m rows, n columns)-10^4 ≤ matrix[i][j], target ≤ 10^4- the time must be O(log(m × n))
The signature is function searchMatrix(matrix: number[][], target: number): boolean. Try it on LeetCode first.
Hint
Read the rows one after another, left to right. What do you get?
Interviewer: Tell me whether this number is in the grid.
Candidate: Each row is sorted, and each row starts above where the row before it ended. So if I read the rows one after another, the whole grid is one sorted list. Can the grid be empty?
Interviewer: No, it’s at least 1 by 1, and every row has the same length.
Candidate: Can numbers repeat?
Interviewer: Inside a row, yes.
Candidate: I only return true or false, so repeats don’t change the answer. Here’s my example, a grid of 4 rows and 3 columns, and three edge cases.
matrix target expected
[[2, 4, 6], [9, 12, 15], [20, 25, 31], [40, 41, 47]] 25 true
the same grid 16 false in a gap
the same grid 47 true last cell
[[7]] 8 false 1 by 1
Candidate: The naive solution looks at every cell.
// O(m * n) time, O(1) memory: looks at every cell.
export function searchMatrixScan(matrix: number[][], target: number): boolean {
for (const row of matrix) {
for (const value of row) {
if (value === target) return true;
}
}
return false;
}
Candidate: That’s O(m × n) time, at most 10⁴ cells, so the clock allows it. Memory is O(1). But the page asks for O(log(m × n)), so this breaks the rule.
Interviewer: What does the scan ignore?
Candidate: The order. Only one row can hold the target: the last row whose first number is at or below it. A binary search on the first numbers finds that row, and a second one searches inside it.
// O(log m + log n) time, O(1) memory: one binary search for the last row whose first number is <= target,
// then one binary search inside that row.
export function searchMatrixTwoSearches(matrix: number[][], target: number): boolean {
let lo = 0;
let hi = matrix.length - 1;
let row = -1;
while (lo <= hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (matrix[mid][0] <= target) {
row = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
if (row === -1) return false;
const values = matrix[row];
lo = 0;
hi = values.length - 1;
while (lo <= hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (values[mid] === target) return true;
if (values[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return false;
}
Candidate: If no row starts at or below the target, row stays -1, and the target is below the whole grid. That’s O(log m + log n) time, which is O(log(m × n)), and O(1) memory.
Interviewer: Can you do it with one loop?
Candidate: Yes. I number the cells 0 to m × n – 1 in reading order, as if the grid were one flat list. Then I run 704’s search on those positions, and turn a position into a cell only to read it.
Figure 2 shows the Candidate’s grid with each cell’s position.
col 0 col 1 col 2 positions
row 0 [2] [4] [6] 0 1 2
row 1 [9] [12] [15] 3 4 5
row 2 [20] [25] [31] 6 7 8
row 3 [40] [41] [47] 9 10 11
position 7 is row Math.floor(7 / 3) = 2, column 7 % 3 = 1: value 25
Figure 2: because the rows are chained, positions 0 to 11 form one sorted list, and dividing by the row length turns a position into a cell with no copy.
// O(log(m * n)) time, O(1) memory: one binary search over positions 0 .. m*n - 1;
// position p is row Math.floor(p / n), column p % n.
function searchMatrix(matrix: number[][], target: number): boolean {
const cols = matrix[0].length;
let lo = 0;
let hi = matrix.length * cols - 1;
while (lo <= hi) {
const mid = lo + Math.floor((hi - lo) / 2);
const value = matrix[Math.floor(mid / cols)][mid % cols];
if (value === target) return true;
if (value < target) lo = mid + 1;
else hi = mid - 1;
}
return false;
}
export { searchMatrix };
Candidate: I divide by the number of columns, not the number of rows. In a square grid both give the same cell, so a square test wouldn’t catch that mistake.
Interviewer: Trace 25.
Figure 3 traces the search for 25. The cell column is (row, column).
step lo hi mid cell value then
1 0 11 5 (1, 2) 15 15 < 25: lo = 6
2 6 11 8 (2, 2) 31 31 > 25: hi = 7
3 6 7 6 (2, 0) 20 20 < 25: lo = 7
4 7 7 7 (2, 1) 25 found: return true
Figure 3: the search halves the range of positions, not of rows, so 12 cells need four looks.
Candidate: For 16, the first three middles are the same. But 20 is larger than 16, so hi becomes 5, the range [6, 5] is empty, and I return false.
Interviewer: Final cost?
Candidate: O(log(m × n)) time: one halving loop over m × n positions, at most 14 looks for 10⁴ cells. O(1) memory: there’s no copy of the grid.
Interviewer: What if each row and each column is sorted, but a row can start below the end of the row before?
The Candidate’s answer
Candidate: Then the positions aren’t one sorted list anymore. I start at the top-right cell. If it’s larger than the target, the whole column below it is larger too, so I move left. If it’s smaller, the whole row to its left is smaller, so I move down.
Candidate: Each step drops a row or a column, so it’s O(m + n) time and O(1) memory.
That’s LeetCode’s 240. Search a 2D Matrix II, which this course doesn’t cover. This version isn’t in the lab.
Interviewer: Two searches or one: which would you write?
The Candidate’s answer
Candidate: Both are O(log(m × n)) and need about the same number of looks: at most 7 + 7 for two searches, 14 for one. One search is less code. Two searches avoid the division and the remainder, and they’re easier to explain row by row.
Candidate: Either one is a good answer, as long as I can say why it’s correct.
Two mistakes are common here:
- Dividing by the number of rows.
matrix[Math.floor(p / m)][p % m]reads the wrong cells when the grid isn’t square. On the Candidate’s 4 by 3 grid, 41 returnsfalseinstead oftrue. Divide by the row length. - Copying the grid first.
matrix.flat()and then a binary search gives the right answer, but the copy costs O(m × n) time and memory, which breaks the page’s rule. Turn positions into cells instead.
Lab folder: module-05/0074-search-a-2d-matrix/ in the course repository.
153. Find Minimum in Rotated Sorted Array
153. Find Minimum in Rotated Sorted Array is rated Medium. A rotation moves the last number of a list to its front, so [10, 20, 30, 40, 50] rotated three times is [30, 40, 50, 10, 20]. You get a sorted list of distinct integers that was rotated some number of times, and you return its smallest number.
1 ≤ n ≤ 5000(n =nums.length)-5000 ≤ nums[i] ≤ 5000, all distinct- rotated 1 to n times; n rotations give back the sorted list
- the time must be O(log n)
The signature is function findMin(nums: number[]): number. Try it on LeetCode first.
Hint
Compare the middle number with the last number of the range. Which side of the drop is the middle on?
Interviewer: This sorted list was rotated. Find its smallest number.
Candidate: So the list rises, drops once, and rises again, and the minimum is right after the drop. Are the numbers distinct?
Interviewer: Yes.
Candidate: Can it be rotated all the way round, so it’s sorted again?
Interviewer: Yes.
Candidate: Then there’s no drop, and the minimum is the first number. Do I return the number or its index?
Interviewer: The number.
Candidate: Here’s my example and three edge cases.
nums expected
[30, 40, 50, 10, 20] 10 the drop is between 50 and 10
[7] 7 one number
[2, 1] 1 two numbers, rotated
[1, 2, 3, 4, 5] 1 not rotated
Candidate: The naive solution reads every number and keeps the smallest.
// O(n) time, O(1) memory: looks at every number.
export function findMinLinear(nums: number[]): number {
let min = nums[0];
for (const value of nums) {
if (value < min) min = value;
}
return min;
}
Candidate: That’s O(n) time, at most 5,000 reads, and O(1) memory. The clock allows it, but the page asks for O(log n).
Interviewer: What does the scan ignore?
Candidate: The list is two sorted runs, and every number in the first run is larger than every number in the second. So the last number tells me which run any index is in.
Candidate: For each index I ask, “is this number at or below the last number?” It’s false in the first run and true from the minimum on. That’s a monotone question, and the minimum is its first yes.
Candidate: If nums[mid] is above nums[hi], the drop is right of mid, so lo = mid + 1. Otherwise mid is in the second run, and the minimum is at mid or left of it, so hi = mid. I stop when lo === hi.
// O(log n) time, O(1) memory: compare mid with the last number of the range. If nums[mid] > nums[hi],
// the drop (and so the minimum) is right of mid; otherwise mid..hi is sorted and the minimum is at mid or left of it.
function findMin(nums: number[]): number {
let lo = 0;
let hi = nums.length - 1;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (nums[mid] > nums[hi]) lo = mid + 1;
else hi = mid;
}
return nums[lo];
}
export { findMin };
Interviewer: Trace your example.
Figure 4 traces [30, 40, 50, 10, 20].
nums [30] [40] [50] [10] [20]
0 1 2 3 4
step lo hi mid nums[mid] nums[hi] then
1 0 4 2 50 20 50 > 20: drop is right, lo = 3
2 3 4 3 10 20 10 <= 20: keep mid, hi = 3
3 3 3 lo === hi: return nums[3] = 10
Figure 4: the last number of the range tells which run the middle is in, and the range closes on the first number of the second run.
Pause and predict. On the unrotated [1, 2, 3, 4, 5], which way does each step move, and what does findMin return?
Candidate: The middle is never above the last number, so every step keeps mid and moves hi left: to 2, then 1, then 0. It returns nums[0], which is 1.
Interviewer: Final cost?
Candidate: O(log n) time: at most 13 looks for 5,000 numbers. O(1) memory.
Interviewer: What if numbers can repeat?
The Candidate’s answer
Candidate: Then nums[mid] === nums[hi] doesn’t tell me which run mid is in. But dropping the last number is safe, because its value is still in the range at mid. So in that case I do hi--.
Candidate: A list of equal numbers with one smaller number drops one index per step, so the worst case is O(n).
That’s LeetCode’s 154. Find Minimum in Rotated Sorted Array II, rated Hard, which this course doesn’t cover. This version isn’t in the lab.
Interviewer: How many times was the list rotated?
The Candidate’s answer
Candidate: The index of the minimum, which is lo when the loop ends. For my example that’s 3, and for an unrotated list it’s 0.
Two mistakes are common here:
hi = mid - 1when the middle is in the second run. The middle may be the minimum itself, and this throws it away.[4, 5, 1, 2, 3]returns4instead of1. Keep it withhi = mid, and loop whilelo < hi.- Comparing with
nums[lo]. On an unrotated list, the middle is always at or above the first number, so the search walks right.[1, 2, 3, 4, 5]returns5instead of1. Compare withnums[hi].
Lab folder: module-05/0153-find-minimum-in-rotated-sorted-array/ in the course repository.
33. Search in Rotated Sorted Array
33. Search in Rotated Sorted Array is rated Medium. You get a sorted list of distinct integers that may have been rotated, as in 153, and a target. Return the target’s index, or -1 if it isn’t there.
1 ≤ n ≤ 5000(n =nums.length)-10^4 ≤ nums[i], target ≤ 10^4, all ofnumsdistinct- the list may be rotated or not
- the time must be O(log n)
The signature is function search(nums: number[], target: number): number. Try it on LeetCode first.
Hint
Split the range at its middle. At least one of the two halves is sorted. How can you tell which, and whether the target is in it?
Interviewer: Find this number in a rotated sorted list.
Candidate: The same shape as before: the list rises, drops at most once, and rises again. Are the numbers distinct?
Interviewer: Yes.
Candidate: Can it be unrotated?
Interviewer: Yes.
Candidate: And a missing target gives -1?
Interviewer: Yes.
Candidate: Here’s my example and three edge cases.
nums target expected
[30, 40, 50, 10, 20] 10 3
[30, 40, 50, 10, 20] 45 -1 between 40 and 50
[1, 2, 3, 4, 5] 4 3 not rotated
[3, 1] 1 1 two numbers
Candidate: The naive solution is the scan from 704, searchLinear. It’s O(n) time, at most 5,000 reads, and O(1) memory. The clock allows it, but the page asks for O(log n).
Interviewer: What does the scan ignore?
Candidate: Both runs are sorted. I already know how to find the drop: 153’s search returns the index of the smallest number. Then the target can only be in one of the two runs, and I search that run with 704’s search.
// O(log n) time, O(1) memory: one binary search finds where the rotation starts (the smallest number),
// a second one searches the sorted half that can hold target.
export function searchFindRotation(nums: number[], target: number): number {
let lo = 0;
let hi = nums.length - 1;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (nums[mid] > nums[hi]) lo = mid + 1;
else hi = mid;
}
const start = lo; // index of the smallest number
if (target >= nums[start] && target <= nums[nums.length - 1]) {
lo = start;
hi = nums.length - 1;
} else {
lo = 0;
hi = start - 1;
}
while (lo <= hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (nums[mid] === target) return mid;
if (nums[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
Candidate: If the target lies between the smallest number and the last number, it’s in the second run. Otherwise it can only be in the first. That’s two binary searches, so O(log n) time and O(1) memory.
Interviewer: Can you do it in one pass?
Candidate: Yes. The drop is on one side of the middle at most, so at least one half, [lo, mid] or [mid, hi], is sorted. If nums[lo] <= nums[mid], the left half is.
Candidate: A sorted half’s numbers lie between its two ends. So I check whether the target lies between them. If it does, I keep that half; if not, I keep the other one.
// O(log n) time, O(1) memory: one binary search. At every mid, one of the halves [lo, mid] or [mid, hi]
// is sorted; check whether target lies inside that sorted half, and keep the half that can hold it.
function search(nums: number[], target: number): number {
let lo = 0;
let hi = nums.length - 1;
while (lo <= hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (nums[mid] === target) return mid;
if (nums[lo] <= nums[mid]) {
// left half [lo, mid] is sorted
if (nums[lo] <= target && target < nums[mid]) hi = mid - 1;
else lo = mid + 1;
} else {
// right half [mid, hi] is sorted
if (nums[mid] < target && target <= nums[hi]) lo = mid + 1;
else hi = mid - 1;
}
}
return -1;
}
export { search };
Interviewer: Trace your example.
Figure 5 traces the search for 10.
nums [30] [40] [50] [10] [20]
0 1 2 3 4
step lo hi mid nums[mid] sorted half then
1 0 4 2 50 left, 30 to 50 10 isn't in it: lo = 3
2 3 4 3 10 found: return 3
Figure 5: one half is always sorted, and its two ends say whether the target can be inside, so each look still drops half the range.
Pause and predict. For the target 45, which half does the first look keep, and how does the search end?
Candidate: The left half, 30 to 50, is sorted and 45 lies between its ends, so hi = 1. Then 30 and 40 are checked, and both are smaller than 45. lo passes hi, and I return -1.
Interviewer: Final cost?
Candidate: O(log n) time: one halving loop, at most 13 looks for 5,000 numbers. O(1) memory.
Interviewer: What if numbers can repeat?
The Candidate’s answer
Candidate: When nums[lo], nums[mid] and nums[hi] are equal, I can’t tell which half is sorted. Then I drop one end with lo++ and look again. A list of equal numbers but one makes that happen at every step, so the worst case is O(n).
That’s LeetCode’s 81. Search in Rotated Sorted Array II, which this course doesn’t cover. This version isn’t in the lab.
Interviewer: You have two answers. Which one would you write in an interview?
The Candidate’s answer
Candidate: Both are O(log n) time and O(1) memory. The two-search version reuses two loops I already trust, so it’s easier to get right under time. The one-pass version is shorter, but its four range checks are easy to get wrong by one.
Candidate: I’d say both, and write the one I can test faster.
Two mistakes are common here:
<instead of<=in the sorted-half check. Whenlo === mid, the left half is one sorted number. Butnums[lo] < nums[mid]is false there, so the code checks the wrong half.[3, 1]with target 1 returns-1instead of1. Use<=.- 704’s search on a rotated list. It compares only the middle with the target, so it goes the wrong way across the drop. On the Candidate’s example, 10 returns
-1instead of3.
Lab folder: module-05/0033-search-in-rotated-sorted-array/ in the course repository.
981. Time Based Key-Value Store
981. Time Based Key-Value Store is rated Medium. You build a store that keeps every version of a key’s value, each with the time it was set. A read for a key at time t returns the version set last at or before t, or the empty string if there is none.
- keys and values have 1 to 100 characters, lowercase letters and digits
1 ≤ timestamp ≤ 10^7- the timestamps of
setcalls strictly increase - at most
2 × 10^5calls tosetandgetin total
LeetCode’s TypeScript template is a class TimeMap with a constructor, set(key: string, value: string, timestamp: number): void and get(key: string, timestamp: number): string. Try it on LeetCode first.
Hint
The timestamps of set only go up. What does that make each key’s list of timestamps?
Interviewer: Build a key-value store that remembers every version of a value.
Candidate: So set adds a version with its time, and get returns the latest version at or before the time it’s given. Do the times of set calls only go up?
Interviewer: Yes, strictly, across all keys.
Candidate: Then each key’s versions arrive in time order, and appending keeps them sorted. What does get return for an unknown key, or a time before the first version?
Interviewer: The empty string.
Candidate: If I ask for exactly a stored time, do I get that version?
Interviewer: Yes. “At or before” includes it.
Candidate: With 2 × 10⁵ calls, one key can get 10⁵ versions and then 10⁵ reads. So a read must cost less than O(k), for a key with k versions.
Candidate: Here’s my example, a door code that changes, with three edge cases.
calls get returns
set door 1111 at 10, 2222 at 20, 3333 at 30
get door 25 "2222"
get door 9 "" before the first one
get door 30 "3333" exactly a stored time
get door 99 "3333" after the last one
Candidate: The naive solution keeps a Map from each key to its list of versions. set appends, and get walks the list from the oldest version and keeps the last one at or before t.
The Candidate writes TimeMapScan, the class at the top of this page.
Candidate: set is amortized O(1), the cost of a push. get is O(k) for a key with k versions. At the limit, that’s 10⁵ reads of up to 10⁵ versions, about 10¹⁰ steps, so it’s too slow.
At that limit, TimeMapScan took 4,250.1 ms with random read times, and 11,602.6 ms when every read asked for the latest time. atlimit.ts times one run of each, so the numbers are rough, and yours will differ.
Interviewer: What does it repeat?
Candidate: Each read walks over times that are already in order. A key’s times are a sorted list, so I can binary search them.
Candidate: I want the last time at or before t. That’s the index one before the first time that is more than t.
The first index whose value is at least t is the lower bound of t, and the first index whose value is more than t is its upper bound. So the Candidate wants the upper bound of t, minus one.
That search runs on a half-open range [lo, hi), which includes lo and excludes hi. It starts with hi = times.length, one past the end, because “no time is more than t” is a possible answer.
Candidate: I keep each key’s times and values in two arrays of the same length, so the search reads plain numbers.
// set O(1) amortized; get O(log k): the timestamps of a key are sorted, so get binary searches
// for the last timestamp <= t. Memory O(total sets) for both classes.
class TimeMap {
times = new Map<string, number[]>();
values = new Map<string, string[]>();
constructor() {}
set(key: string, value: string, timestamp: number): void {
const times = this.times.get(key);
if (times) {
times.push(timestamp);
this.values.get(key)!.push(value);
} else {
this.times.set(key, [timestamp]);
this.values.set(key, [value]);
}
}
get(key: string, timestamp: number): string {
const times = this.times.get(key);
if (!times) return "";
// find the first index whose time is > timestamp; the answer is just before it
let lo = 0;
let hi = times.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (times[mid] <= timestamp) lo = mid + 1;
else hi = mid;
}
return lo === 0 ? "" : this.values.get(key)![lo - 1];
}
}
export { TimeMap };
Candidate: If times[mid] is at or before t, the upper bound is right of mid, so lo = mid + 1. Otherwise mid could be the upper bound, so hi = mid. When the loop ends, lo is the upper bound, and the answer is values[lo - 1], or "" when lo is 0.
Interviewer: Trace get door 25.
Figure 6 traces it. Index 3 is one past the end of times.
times [10] [20] [30]
values "1111" "2222" "3333"
0 1 2 3
step lo hi mid times[mid] then
1 0 3 1 20 20 <= 25: lo = 2
2 2 3 2 30 30 > 25: hi = 2
3 2 2 lo === hi: upper bound 2, return values[1]
Figure 6: the search finds the first time after 25, and the version before it, “2222”, is the latest one at or before 25.
Candidate: For get door 9, every time is after 9, so hi moves down to 0 and lo stays at 0. There’s no version before index 0, so I return "".
Candidate: For get door 30, the time 30 is at or before 30, so lo moves past it and ends at 3. values[2] is “3333”, the exact match.
Interviewer: Final cost?
Candidate: set is amortized O(1): two pushes. get is O(log k): about 17 looks for 10⁵ versions. Memory is O(total sets), for the two arrays.
In the same run of atlimit.ts, TimeMap took 28.2 ms with random read times and 13.8 ms with the latest time, against 4,250.1 ms and 11,602.6 ms for the scan.
Interviewer: What if set times can arrive out of order?
The Candidate’s answer (stretch)
Candidate: Then appending doesn’t keep the list sorted. I can insert each version at its upper bound with splice, but that shifts every later item, so set becomes O(k).
Candidate: For O(log k) on both set and get, I’d need a sorted structure, such as a balanced search tree or a skip list. JavaScript doesn’t ship one, so I’d have to write it.
The keyed collections in ECMAScript 2025 are Map, Set, WeakMap and WeakSet, and a Map visits its keys in the order they were inserted, not sorted. This version isn’t in the lab.
Interviewer: Most reads ask for the latest version. Would you still binary search?
The Candidate’s answer
Candidate: A scan from the newest end stops at once for those reads, so it’s O(1) for them and the code is simpler. But a read for an old time still costs O(k).
Candidate: If I know the reads are almost all recent, the backward scan is a fair choice. If I don’t know, the binary search is O(log k) whatever the reads are.
Interviewer: Memory grows forever. How would you cap it?
The Candidate’s answer
Candidate: I’d keep versions only for a fixed window of time, and drop older ones from the front of each key’s arrays. Removing from the front of an array shifts everything, so I’d keep a start index per key instead and search from there. The deque from DSA Module 5 would also work.
This version isn’t in the lab.
Two mistakes are common here:
- Searching for the first time at or after t. Testing
times[mid] < tfinds the lower bound, and the version before it skips an exact match. Afterset door 1111 at 10andset door 2222 at 20,get door 20returns"1111"instead of"2222". Testtimes[mid] <= t. - A plain object as the key table.
constructoris a legal key, and every plain object inherits aconstructorproperty fromObject.prototype. Sothis.times["constructor"]is theObjectfunction, andset("constructor", "x", 1)throwsTypeError: this.times[key].push is not a function. Use aMap, which has no inherited keys.
Lab folder: module-05/0981-time-based-key-value-store/ in the course repository.
4. Median of Two Sorted Arrays
4. Median of Two Sorted Arrays is rated Hard. You get two sorted lists of integers; one may be empty, but not both. Return the median of all their numbers together: the middle number when the count is odd, or the average of the two middle numbers when it’s even.
0 ≤ m, n ≤ 1000and1 ≤ m + n ≤ 2000(m =nums1.length, n =nums2.length)-10^6 ≤ nums1[i], nums2[i] ≤ 10^6- the time must be O(log(m + n))
The signature is function findMedianSortedArrays(nums1: number[], nums2: number[]): number. Try it on LeetCode first.
Hint
Say the lower half of all the numbers takes i numbers from the front of nums1. How many does it take from nums2, and how can you check that i is right?
Interviewer: Find the median of these two sorted lists together.
Candidate: Can one list be empty?
Interviewer: Yes, but not both.
Candidate: For an even count, I average the two middle numbers, so the answer can be a fraction?
Interviewer: Yes.
Candidate: Can numbers repeat, inside a list or across both?
Interviewer: Yes.
Candidate: Here’s my example and three edge cases.
nums1 nums2 expected
[2, 9, 15] [4, 6, 11, 20] 9 seven numbers: the 4th
[2, 9, 15] [4, 6, 11] 7.5 six numbers: (6 + 9) / 2
[] [5] 5 one list empty
[1, 2, 3] [7, 8, 9] 5 one list below the other
[1, 1, 1] [1, 1] 1 repeats
Candidate: The naive solution joins both lists, sorts, and reads the middle.
// O((m + n) log(m + n)) time, O(m + n) memory: join both arrays, sort, read the middle.
export function medianSort(nums1: number[], nums2: number[]): number {
const all = [...nums1, ...nums2].sort((a, b) => a - b);
const mid = Math.floor(all.length / 2);
return all.length % 2 === 1 ? all[mid] : (all[mid - 1] + all[mid]) / 2;
}
Candidate: The sort is O((m + n) log(m + n)) time, about 2.2 × 10⁴ steps at 2,000 numbers, so the clock allows it. Memory is O(m + n) for the copy. But the page asks for O(log(m + n)).
Interviewer: What does it repeat?
Candidate: It sorts numbers that are already sorted. A merge takes numbers in sorted order with one index per list. And I only need to walk as far as the middle, keeping the last two numbers taken.
// O(m + n) time, O(1) memory: walk both arrays as a merge would, but stop at the middle and keep
// only the last two numbers taken.
export function medianMergeWalk(nums1: number[], nums2: number[]): number {
const total = nums1.length + nums2.length;
let i = 0;
let j = 0;
let previous = 0;
let current = 0;
for (let taken = 0; taken <= Math.floor(total / 2); taken++) {
previous = current;
if (j >= nums2.length || (i < nums1.length && nums1[i] <= nums2[j])) current = nums1[i++];
else current = nums2[j++];
}
return total % 2 === 1 ? current : (previous + current) / 2;
}
Candidate: That’s O(m + n) time, at most 1,001 steps, and O(1) memory. It’s still not logarithmic.
Interviewer: Can you skip the walk?
Candidate: The walk moves one number at a time toward the middle. But I can describe the middle another way. The lower half of all the numbers holds half of them: some i from the front of nums1, and j = half - i from the front of nums2.
The Candidate calls the choice of i a cut. It splits nums1 before index i and nums2 before index j, and the numbers before the two split points form the lower half. With half = Math.floor((m + n + 1) / 2), the lower half holds the extra number when the count is odd.
Candidate: The cut is right when every number on the left is at or below every number on the right. Each list is sorted, so I only check across the lists: nums1[i - 1] <= nums2[j] and nums2[j - 1] <= nums1[i]. A missing neighbor at an end counts as -Infinity or Infinity.
Candidate: If nums1[i - 1] > nums2[j], I took too many from nums1, so i moves left. Otherwise I took too few, and it moves right. As i grows, “too many” switches from false to true once, so I binary search on i.
Candidate: I search the shorter list. With m ≤ n, every i from 0 to m gives a j from 0 to n.
// O(log(min(m, n))) time, O(1) memory: binary search for how many numbers of the shorter array go in the
// left half. A cut is right when every number left of it is <= every number right of it.
function findMedianSortedArrays(nums1: number[], nums2: number[]): number {
if (nums1.length > nums2.length) return findMedianSortedArrays(nums2, nums1);
const m = nums1.length;
const n = nums2.length;
const half = Math.floor((m + n + 1) / 2); // size of the left half; it holds one extra when m + n is odd
let lo = 0;
let hi = m;
while (lo <= hi) {
const i = lo + Math.floor((hi - lo) / 2); // numbers taken from nums1
const j = half - i; // numbers taken from nums2
const left1 = i > 0 ? nums1[i - 1] : -Infinity;
const right1 = i < m ? nums1[i] : Infinity;
const left2 = j > 0 ? nums2[j - 1] : -Infinity;
const right2 = j < n ? nums2[j] : Infinity;
if (left1 <= right2 && left2 <= right1) {
const leftMax = Math.max(left1, left2);
if ((m + n) % 2 === 1) return leftMax;
return (leftMax + Math.min(right1, right2)) / 2;
}
if (left1 > right2) hi = i - 1; // took too many from nums1
else lo = i + 1; // took too few from nums1
}
throw new Error("inputs are not sorted");
}
export { findMedianSortedArrays };
Candidate: Once the cut is right, the median is the largest left number for an odd count. For an even count, it’s the average of that and the smallest right number. The throw at the end only runs if an input isn’t sorted.
Pause and predict. On the Candidate’s first example, half is 4, and the first look tries i = 1. Is that too many numbers from nums1, or too few?
Interviewer: Trace your example.
Figure 7 traces [2, 9, 15] and [4, 6, 11, 20]. nums1 is already the shorter list, so there’s no swap.
half = Math.floor((3 + 4 + 1) / 2) = 4
step lo hi i j left1 right1 left2 right2 then
1 0 3 1 3 2 9 11 20 11 > 9: too few, lo = 2
2 2 3 2 2 9 15 6 11 9 <= 11, 6 <= 15: right
the cut at step 2:
nums1 [2] [9] | [15]
nums2 [4] [6] | [11] [20]
left half right half odd count: median = max(9, 6) = 9
Figure 7: the cut moves in the shorter list only, j follows from it, and two comparisons across the cut say which way to move.
Candidate: At i = 1, the left half takes 11 from nums2, but 9 from nums1 sits on the right and is smaller. So I took too few from nums1, and lo becomes 2.
Candidate: At i = 2, both checks hold. The count, 7, is odd, so the median is the largest left number, max(9, 6) = 9.
Candidate: For [1, 2, 3] and [7, 8, 9], the cut ends at i = 3 and j = 0. right1 is Infinity and left2 is -Infinity, so the checks still hold, and the median is (3 + 7) / 2 = 5.
Interviewer: Final cost?
Candidate: O(log(min(m, n))) time, which is within O(log(m + n)): about 10 looks when the shorter list has 1,000 numbers. O(1) memory.
Interviewer: Can you find the k-th smallest number of the two lists instead?
The Candidate’s answer
Candidate: Yes, with the same cut. The left side holds k numbers instead of half, so j = k - i. I limit i so that j stays between 0 and n, and the answer is the largest left number. It’s still O(log(min(m, n))).
This version isn’t in the lab.
Interviewer: What if the numbers arrive one at a time, and I ask for the median after each one?
The Candidate’s answer (stretch)
Candidate: Then there are no two sorted lists to cut. I’d keep the lower half in a max-heap and the upper half in a min-heap, and keep their sizes within one of each other. Each new number costs O(log n), and the median is read from the tops.
That’s 295. Find Median from Data Stream, in Module 8.
Interviewer: Why search the shorter list?
The Candidate’s answer
Candidate: So every i gives a valid j. If nums1 were longer, j = half - i could fall below 0 or above n. It also makes the cost O(log) of the shorter length.
Three mistakes are common here:
- Integer division for an even count.
Math.floor((a + b) / 2)is a habit from languages with integer types.[1, 2]and[3, 4]return2instead of2.5. Divide with/and keep the fraction. - The default
sort()in the join-and-sort answer. It compares numbers as strings, so10comes before2.[2, 10]and[3]return2instead of3. Pass(a, b) => a - b. - Searching the longer list.
j = half - ican fall outsidenums2, and the cut test reads past its ends. On[1, 2, 3, 4, 5, 6, 7, 8, 9]and[100], the lab version’s search ended with “no cut found”, instead of returning5.5. Swap so thatnums1is the shorter list.
Lab folder: module-05/0004-median-of-two-sorted-arrays/ in the course repository.
Measured: Time Based Key-Value Store, scan against binary search
Time Based Key-Value Store is the problem this module measures, with bench.ts from DSA Module 1. Every input puts n versions on one key, with times that rise by a random gap of 1 to 10, then makes n reads at random times. The scan runs at 10,000, 20,000 and 40,000, because it takes about a second at 40,000. The binary search runs at the same sizes, and again at 100,000 to 400,000, where 100,000 is LeetCode’s limit.
// Module 5 measurement: Time Based Key-Value Store, scanning every stored timestamp on each get
// against a binary search. One key, n sets, then n gets at random times: the scan's worst shape.
// Run from the repository root: node module-05/measure.ts
import { bench } from "../shared/bench.ts";
import { TimeMapScan, TimeMap } from "./0981-time-based-key-value-store/solution.ts";
type Input = { times: number[]; queries: number[] };
// n strictly increasing timestamps (random gaps of 1 to 10) and n random query times within them.
function randomCalls(n: number): Input {
const times: number[] = [];
let t = 0;
for (let i = 0; i < n; i++) {
t += 1 + Math.floor(Math.random() * 10);
times.push(t);
}
const queries = Array.from({ length: n }, () => 1 + Math.floor(Math.random() * t));
return { times, queries };
}
let sink = 0; // the timed functions add to it, so their work cannot be skipped
function run(map: { set(k: string, v: string, t: number): void; get(k: string, t: number): string }, input: Input): void {
for (const time of input.times) map.set("key", "v" + time, time);
for (const q of input.queries) sink += map.get("key", q).length;
}
bench("TimeMapScan (scan every timestamp on each get)", [10_000, 20_000, 40_000], randomCalls, (input) => {
run(new TimeMapScan(), input);
});
bench("TimeMap (binary search on each get)", [10_000, 20_000, 40_000], randomCalls, (input) => {
run(new TimeMap(), input);
});
// 10^5 sets + 10^5 gets is LeetCode's limit of 2 * 10^5 calls.
bench("TimeMap at LeetCode's limit and beyond", [100_000, 200_000, 400_000], randomCalls, (input) => {
run(new TimeMap(), input);
});
console.log(`\nsink ${sink}`);
bench runs each size once to warm up, then five times on fresh inputs, and prints the median and how many times slower each size is than the one before.
Pause and predict. With n versions and n reads, the scan does about n²/2 steps in total, and the binary search about n log n. When n doubles, how many times longer should each one take?
Here is what node module-05/measure.ts printed:
TimeMapScan (scan every timestamp on each get)
n median ms x prev
10,000 54.00
20,000 236.49 4.4
40,000 1024.90 4.3
TimeMap (binary search on each get)
n median ms x prev
10,000 2.04
20,000 4.06 2.0
40,000 8.79 2.2
TimeMap at LeetCode's limit and beyond
n median ms x prev
100,000 23.81
200,000 50.74 2.1
400,000 108.83 2.1
sink 35704800
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.
The scan grew 4.4 and 4.3 times per doubling, which is O(n²) for the whole run: each of n reads walks about half of n versions. It grew a little faster than 4, and we didn’t look into why.
The binary search grew 2.0 to 2.2 times per doubling. That’s O(n log n), and log n changes little between these sizes, so it looks almost linear. At 40,000 the binary search was about 117 times faster (8.79 against 1,024.90 ms), and the gap widens as n grows. sink is the total length of every value returned, so V8 can’t skip the reads.
Underneath: binary search in JavaScript
JavaScript has no built-in binary search on arrays. The ECMAScript draft has none, and no TC39 proposal at Stage 2 or 3 adds one. indexOf, findIndex, findLast and findLastIndex all scan, so they’re O(n) even on a sorted array. That’s why every search in this module is written by hand. It’s only correct on data sorted with a numeric comparator, because sort() with no comparator compares numbers as strings, as a mistake in 4 showed.
The middle of the range has a history. In 2006, Joshua Bloch wrote that (low + high) / 2 in Java’s binary search overflowed a 32-bit int for very large arrays. He gave two fixes: low + ((high - low) / 2) and (low + high) >>> 1.
In JavaScript the overflow can’t happen with indexes. A number is a double, and every integer up to Number.MAX_SAFE_INTEGER, 2⁵³ − 1, is exact. An array’s length is below 2³² (ECMAScript 2025, section 10.4.2), so the sum of two indexes is exact.
But the second fix is a bug in JavaScript. >>> first converts its left side to an unsigned 32-bit integer, a conversion the specification calls ToUint32, so a sum of 2³² or more wraps around. Array indexes never get there, but a binary search over a range of values can. DSA Module 9 ran such a search with >>> 1, and it never ended. So this course writes lo + Math.floor((hi - lo) / 2) everywhere, which is exact for any range below 2⁵³.
981’s store uses a Map for its keys because a Map has no inherited keys. A plain object inherits constructor, toString and others from Object.prototype, which is the bug in 981’s second mistake. DSA Module 3 compares the two.
Cheat sheet
Figure 8 maps each problem in this module to the sign that pointed to its solution.
sign in the problem problem binary search for cost
sorted list, find a value 704 the value, in [lo, hi] O(log n)
rows chained into a sorted list 74 a flat position O(log mn)
sorted, then rotated: smallest 153 first index at or below O(log n)
the last number
sorted, then rotated: find value 33 the value, in the O(log n)
sorted half
latest version at or before t 981 the upper bound of t O(log k)
median of two sorted lists 4 the cut in the shorter O(log m)
list, of length m
Figure 8: when the data is sorted, or a yes-or-no question switches once, one look at the middle drops half the range.
- Pattern: keep the range that can still hold the answer; one look at the middle drops half. Write the middle as
lo + Math.floor((hi - lo) / 2). - Closed range
[lo, hi]: loop whilelo <= hi, return on a match, and move pastmidon each step. - First yes: loop while
lo < hi;hi = midwhenmidcan be the answer,lo = mid + 1when it can’t. Start withhi = nwhen “none” is a possible answer. - Signs: sorted data, or sorted in pieces; a required O(log n); “the latest at or before”, “the first that”; a yes-or-no question that switches once.
- Final costs: 704, 153 and 33 in O(log n); 74 in O(log(m × n)); 981 in O(1) per
setand O(log k) perget; 4 in O(log(min(m, n))). Every one uses O(1) extra memory, except 981’s store of every version. - Next: Module 6 works linked lists, where a pointer that moves twice as fast as another finds a cycle in O(1) memory.
Sources
- LeetCode problem pages, checked on 2026-11-20: 704, 74, 153, 33, 981, 4, and 34, 240, 154 and 81 for follow-ups.
- “binary search”, Dictionary of Algorithms and Data Structures, NIST.
- Joshua Bloch, “Extra, Extra – Read All About It: Nearly All Binary Searches and Mergesorts are Broken”, Google Research blog, 2006.
- ECMAScript 2025 specification:
Number.MAX_SAFE_INTEGER, array exotic objects, ToUint32 and keyed collections. TC39 proposals. - Node.js documentation: assert, TypeScript, test runner.