Skip to content
Tech Interview Prep
Technical interview guide

Binary Search

Halving the search space on sorted data, and the many variants beyond a plain lookup.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v7
Editorial status
Reviewed

Scope: Language-neutral, with library behaviour cited from CPython 3.14 bisect, the C++ standard algorithms, and java.util as of Java 21.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-15

How would you explain the comparison function contract without using the usual slogan?

Answer

The contract has three clauses, and binary search needs all three: the comparator must be total (every pair yields a consistent ordering. NaN breaks this because every NaN < x and x < NaN is false, so the ordering is inconsistent rather than absent), transitive (a<b and b<c implies a<c), and consistent with the order the array was actually sorted with. The last clause is the one people forget: the comparator isn't just a function you hand to bisect, it's a claim about how the data underneath was arranged. Violate any clause and you don't get an exception: you get a confident wrong index, because the elimination step is still doing exactly what it was told to do.

Why it fails silently. Each probe compares once and throws away half the array. If the comparator says arr[mid] < target, the answer must be to the right: that inference only holds under the contract. With a non-transitive comparator (say, a fuzzy string match that's pairwise but not ordered), the true target can sit in the half you just discarded, and nothing downstream will ever look there. O(log n) probes, each one locally reasonable, globally wrong. That's why the failure survives casual testing: a 10-element list with a linear-scan sanity check hides it, and it only shows up at the scale where binary search was worth using in the first place.

The classic bug, concretely:

Python
import bisect

people = sorted([("ana", 34), ("bo", 19), ("cy", 30)], key=lambda p: p[1])
# sorted by age: [("bo", 19), ("cy", 30), ("ana", 34)]
names = [p[0] for p in people]   # ["bo", "cy", "ana"] — not alphabetical

bisect.bisect_left(names, "ana")  # returns 0

Trace: lo=0, hi=3, mid=1, "cy" < "ana" is false so hi=1; mid=0, "bo" < "ana" is false so hi=0; loop ends, returns 0. The correct answer is index 2, that's where "ana" sits, and a linear scan would find it. No exception is raised at any step; the search just eliminated the half containing the answer on its first probe. Python 3.10+ closes the drift risk: bisect.bisect_left(people, 30, key=lambda p: p[1]) keeps the sort key and the search key in one expression, so they can't diverge across a refactor. Before 3.10, the idiom is to extract the key list once and reuse it for both sort and search.

Trade-offs worth naming: if the data is small, under a few hundred elements, a linear scan is O(n) but immune to comparator mismatch, and the constant factors make it just as fast; binary search earns its complexity only when n is large enough that O(n) hurts or the array is searched many times per sort. If you can't guarantee the sort order (data arriving from another service, mutated since sorting), either re-sort with the same comparator or fall back to a scan: don't binary search over an unverified invariant.

How you'd catch it: a property test asserting bisect_left(arr, x) returns an index where everything left of it compares less and everything from it compares greater-or-equal, run against the real comparator on real data. That check fails immediately for a non-transitive or mismatched comparator, and it's cheap enough to run in CI.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Walk through half-open ranges, including where engineers most often get it wrong.

Answer

A half-open range [lo, hi) includes lo and excludes hi. The reason it dominates binary search and slicing is that three properties fall out of the arithmetic, and each one is derivable rather than memorized:

  • Empty means equal. The range holds hi - lo elements, so it's empty exactly when lo == hi. That gives the loop condition while lo < hi and the termination argument for free: every iteration strictly shrinks hi - lo.
  • The midpoint is in range. With mid = (lo + hi) // 2 and lo < hi, we get lo <= mid < hi: integer division of two numbers whose difference is at least 1 can't return hi. So a[mid] is always a valid access, with no special case for the last element.
  • The result is the insertion point. When the loop exits, lo == hi is the boundary between "everything left of it failed the test" and "everything from it on passed", which is exactly where a new element would be inserted, and it ranges over [0, len(a)] with no adjustment.
Python
def lower_bound(a, target):
    lo, hi = 0, len(a)      # search a[lo:hi], hi exclusive
    while lo < hi:          # empty exactly when lo == hi
        mid = (lo + hi) // 2
        if a[mid] < target:
            lo = mid + 1    # discard a[lo..mid] inclusive
        else:
            hi = mid        # discard a[mid..hi)
    return lo               # insertion point, in [0, len(a)]

Trace it with a = [2, 4, 6], target = 5:

steplohimida[mid]action
103144 < 5 → lo = 2
223266 >= 5 → hi = 2
exit22——return 2

a[2] = 6 is the first element >= 5, so 2 is the insertion point. Note both updates shrink the range (mid + 1 > lo always; mid < hi always), which is the termination proof.

Where it goes wrong. The classic bug is mixing conventions: an inclusive hi = len(a) - 1 with the half-open update hi = mid. Then hi can land on an element already examined, and with a two-element range mid == lo, the hi = mid branch makes no progress: infinite loop. The mirror bug, exclusive hi with hi = mid - 1, can step to mid - 1 == lo - 1 and skip the answer or run past index 0. Both survive casual tests because they only trigger on specific parities and lengths; a two-element array or an absent target is usually what exposes them, which is exactly what ad-hoc testing omits. The other recurring error is returning a[lo] instead of lo: fine until the target is absent and lo == len(a).

When not to use it. Half-open isn't universal. Rust's Range types and Go's slices are half-open, so it's the native idiom there; but a closed range [lo, hi] is preferable when the domain is inherently inclusive: dates on a calendar ("Jan 1 through Jan 31"), inclusive integer intervals in math libraries, or protocol fields that specify a maximum value. Closed ranges pay for that with messier arithmetic: element count is hi - lo + 1, the empty case is lo > hi rather than lo == hi, and the midpoint needs mid = (lo + hi + 1) // 2 in some formulations to avoid stalling. Java's Arrays.binarySearch also returns a negative insertion encoding rather than the index itself, so the "insertion point" property is a convention of your own loop, not of the library.

The interview-ready summary: half-open bounds make emptiness, midpoint validity, and the insertion point all follow from lo < hi, at the cost of remembering that hi is never a valid index. State the convention in a comment above the loop, and test the two-element and absent-target cases explicitly.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

What does midpoint overflow guarantee, and what does it deliberately leave open?

Answer

The 90-second answer. The safe midpoint is lo + (hi - lo) / 2. It guarantees two things: no intermediate value ever exceeds hi, so nothing overflows for any valid pair of indices, and the result lands in [lo, hi]. What it deliberately leaves open is the rounding direction, floor or ceiling, and therefore which of the two middle elements you get when the span is odd. That choice is not part of the overflow guarantee; it is a separate decision you make to match your loop's update rule.

Why it stays in range. hi - lo is the span. Since lo >= 0, the span is at most hi, so it fits in whatever type holds hi. Half the span is at most span/2, and lo + span/2 <= lo + (hi - lo) = hi. Every intermediate is bounded by hi, and the sum lo + hi, the value that overflows, is never formed. The naive (lo + hi) / 2 forms that sum: for lo = hi = 2^31 - 1 it is 2^32 - 2, past the signed 32-bit max of 2^31 - 1.

What it leaves open. Both lo + (hi - lo) / 2 (floor) and lo + (hi - lo + 1) / 2 (ceiling) are overflow-safe. They differ only when the span is odd, and that difference decides termination. With a floor midpoint, hi = lo + 1 gives mid = lo; if your update is lo = mid you never advance and loop forever. Pair floor with lo = mid + 1, or ceiling with hi = mid - 1. The overflow fix says nothing about which pairing you chose: that is the open part.

Alternatives.

FormOverflow-safeRoundingCost
lo + (hi - lo) / 2yesfloorone subtract, one divide
(lo + hi) >>> 1 (Java/C#)yesfloorone add, one shift
(int)(((long)lo + hi) / 2)yesfloorwiden, add, divide, narrow
(lo + hi) / 2nofloorone add, one divide
(lo + hi) / 2 on unsigneddefined, still wrong—wraps below lo

>>> works because lo + hi < 2^32 for non-negative 32-bit ints, so the unsigned shift recovers the true floor even after the signed sum wraps. Unsigned types in C do not help: the wrap is defined but the quotient is a midpoint below lo.

Failure mode. The bug is an infinite loop, not a wrong answer: the search never narrows. It hides because it only triggers when hi = lo + 1 and the target sits at hi. Joshua Bloch documented in 2006 that (low + high) / 2 in java.util.Arrays.binarySearch had overflowed for nine years; the same pattern sat in the JDK's merge sort.

Trace. Array [10, 20], target 20. lo = 0, hi = 1. Floor mid = 0 + (1 - 0) / 2 = 0. a[0] = 10 < 20, so the correct update is lo = mid + 1 = 1. Now lo == hi == 1, the loop ends, return 1. With the wrong update lo = mid, lo stays 0 and the loop spins forever.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Explain the halving argument and how it changes a production decision.

Answer

The halving argument is the proof that binary search costs O(log n): each comparison eliminates half of the remaining candidates, so after k probes at most n/2^k remain, and you need k ≥ log₂(n) probes to reduce that to one. A billion sorted elements take at most 30 probes (2³⁰ ≈ 1.07 billion); a trillion take 40. That is the whole argument, but it carries a precondition that decides whether you can use it in production: the elimination step must be sound, which requires the data to be sorted by the same key you probe with, and the comparison to be consistent with that ordering.

The invariant that makes each halving step legitimate: if the target exists, it lies in a[lo:hi], and every branch preserves that.

Python
# Invariant: if target is present, it lies in a[lo:hi].
lo, hi = 0, len(a)
while lo < hi:
    mid = lo + (hi - lo) // 2
    if a[mid] < target: lo = mid + 1   # a[:mid+1] all smaller, cannot contain it
    else:              hi = mid       # a[mid:] all >= target, answer is mid or left

The production decision it actually changes. Suppose a service does point lookups of user IDs against a 200-million-row table that is rebuilt nightly. Three options:

OptionLookup costExtra costWhen it wins
Sorted array + binary search~28 probes, all cache-friendly if the array fits in memoryNightly sort; lookups see up to 24h stalenessData is static between builds, memory is tight, or you also need range scans
Hash index (e.g. a hash map or database B-tree with hash)~1 probe, O(1)~2–3x the memory for the index; no range queriesFreshness or per-request latency dominates
Linear scanO(n), ~200M comparisonsNonen is small (tens to low hundreds of rows): the constant factor of binary search loses to a tight scan loop, and branch prediction loves sequential access

The halving argument is what licenses the first row: 28 probes at, say, 100 ns each (mostly L2/L3 cache hits on a contiguous array) is ~3 µs per lookup, with no per-request index maintenance. The same argument tells you when it's the wrong call: if the data mutates between requests, keeping an array sorted costs O(n) per insert or an O(log n) rebalance via a B-tree. At which point the database's B-tree gives you the same log₂ behavior with online updates, and binary search over a raw array stops being the right primitive.

Failure modes worth naming. The classic one is a subtly broken invariant: an off-by-one in the branch, or data sorted by a different collation than the probe uses (case-insensitive sort, then a case-sensitive comparison). It survives casual testing because the happy path hides it; it surfaces as a lookup that misses rows that exist. Detection: property-test the invariant directly. For random targets, assert that a miss is truly absent by checking the boundary neighbors, and fuzz with duplicates at the boundaries. The second failure is staleness: the nightly rebuild means a user created this morning is invisible to lookups. If that breaks the product, the sorted-array design is wrong regardless of how fast the probes are.

So the shape of the answer: the halving argument gives you the cost curve (30 probes for a billion), the invariant gives you the correctness condition, and the decision turns on mutation rate, freshness requirements, and whether you need range queries, not on the probe count alone.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

Describe termination and the evidence you would collect before relying on it.

Answer

Termination is a proof obligation, not an observation. The evidence I'd collect is a strictly decreasing measure, a loop variant, plus a demonstration that every path through the loop body reduces it. For loops, that measure is usually an integer bounded below; for recursion, it's a well-founded ordering on the arguments, like a shrinking list or a decreasing depth. If I can name the measure and show every branch shrinks it, termination is settled by argument, not by testing, and if I can't, no amount of testing settles it.

The core answer in an interview: state the variant, check every branch against it, and say what evidence would change your mind. Testing can only falsify termination (by hanging); it can never confirm it.

The classic worked example is binary search with an inclusive high bound:

Python
# Python 3. a = [1, 2], target = 2, lo = 0, hi = 1
while lo < hi:
    mid = lo + (hi - lo) // 2   # floor division: mid = 0
    if a[mid] < target:
        lo = mid + 1            # lo increases: variant shrinks
    else:
        hi = mid                # hi decreases: variant shrinks

Trace it: lo=0, hi=1, mid=0, a[0]=1 < 2, so lo=1. Now lo=1, hi=1, the guard lo < hi fails, loop exits. The variant is hi - lo, bounded below by 0 and positive on entry; both branches reduce it by at least 1, so this terminates for any input data: the branches shrink unconditionally, regardless of what the array contains. That's worth stating explicitly: this loop's termination doesn't depend on the array being sorted. Sortedness is a correctness precondition (the result is meaningless without it), not a termination precondition.

The bug appears when someone writes lo = mid instead of lo = mid + 1: with lo=0, hi=1, mid=0 on every iteration and the loop never exits. Floor division rounds toward the low bound, so hi = mid is always safe when lo < hi, but a taken lo = mid branch needs mid > lo to make progress.

That points at the two standard patterns and when each applies:

  • Lower-bound style (lo = mid + 1, hi = mid, floor division): finds the first index satisfying a predicate. Both branches shrink with floor division. This is the default I reach for: the invariant "the answer, if it exists, is in [lo, hi]" is easy to state and check.
  • Upper-bound style (lo = mid, hi = mid - 1, ceiling division via mid = (lo + hi + 1) // 2): finds the last index satisfying a predicate. Here lo = mid is required, so the midpoint must round up; with floor division and lo = 0, hi = 1, mid = 0 and lo = mid loops forever. The +1 forces mid > lo whenever lo < hi, so the taken branch strictly increases lo.

The rule underneath both: the rounding direction and the branch assignments must agree. If a branch keeps mid in the range (lo = mid or hi = mid), the midpoint must round away from that side; if it discards mid (mid ± 1), either rounding works.

What I'd actually collect before relying on termination:

EvidenceWhat it establishesWhat it doesn't
Named variant + per-branch reductionTermination for all inputsNothing: this is the proof
Exhaustive test over small ranges (e.g. all lo, hi pairs up to 20)Catches the classic off-by-one bugs cheaplyDoesn't generalize to large inputs by itself
Timeout/fuzz run at realistic scaleCatches termination that depends on dataA pass is weak evidence

The third row matters for loops where the variant is data-dependent: while a[i] != x: i += 1 terminates only if x is actually present, and a graph traversal with a visited set terminates only if the graph is finite. Those are the cases where the proof has a precondition on the input, and I'd pair it with a cheap runtime check (a bound on iterations, an assertion on the debug path) rather than trusting the caller. For the binary search above, no such check is needed: the proof is unconditional.

For recursion, the same structure applies with a different measure: each call must consume from a well-founded set. A shorter list, a smaller subtree, a decreased integer. Mutual recursion is where people get caught: A calls B calls A, and the measure has to decrease across the whole cycle, not just each individual call.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

How would you brief product on why the logarithm's base and practical depth delays a ship date?

Answer

Assume the question means: engineering wants an extra sprint because a feature that looks "logarithmic and therefore fast" on paper has real depth-dependent costs, and I need to explain to product why the math doesn't get us to the ship date. If the interviewer means something narrower, a specific data structure's depth, I'd ask which one, but the briefing shape is the same.

The 60-second version for product: the base of a logarithm doesn't matter for the growth curve, changing base multiplies by a constant, but the practical depth of the structure does matter, because each level costs a real operation: a disk seek, a network hop, a lock acquisition. Depth is where "logarithmic" stops being a synonym for "instant."

Why base is a red herring. log₂(n) and log₁₀(n) differ only by a constant factor: log₂(n) = log₁₀(n) / log₁₀(2), and 1/log₁₀(2) = ln(10)/ln(2) ≈ 3.32. A trillion-element index is 40 levels in base 2, 12 in base 10: same curve, different units. This is why engineers quote big-O and don't argue about base: it never changes which design wins at scale. So when engineering says "the log base," they're not padding the estimate with math trivia.

Why depth still delays the ship. Each level of a tree or each step of a search costs a round trip, not a nanosecond:

StructureDepth at 1B keysCost per levelTotal worst case
Binary search, sorted array in RAM30~100 ns cache miss~3 µs
B-tree index (fan-out 128)5~10 ms disk/network read~50 ms
Linked list walked as "search"1B~100 ns~100 s

Same "O(log n)" label on the first two rows; a ~17,000× difference in latency (50 ms / 3 µs). That gap is the entire product conversation: p99 search latency of 50 ms versus 3 µs is the difference between shipping and holding.

The concrete failure that costs the sprint. Suppose the feature is a lookup service on a B-tree with fan-out 128. At 1B keys that's 5 levels (128⁵ ≈ 3.4×10¹⁰ > 10⁹), and the top levels stay cached, so the first 3 levels are ~microseconds and the last 2 are disk reads at ~10 ms each, giving ~20–50 ms worst case. Casual testing on a 10M-key dataset shows 4 levels (128⁴ ≈ 2.7×10⁸ > 10⁷), and if the top 3 of those are cached, only the leaf read hits disk: ~10 ms, and everyone signs off. At production scale the second-to-last level also falls out of cache and p99 doubles to ~20–50 ms. You detect it by load-testing at the real key count with a cold-ish cache and watching the per-level read counters; you fix it by raising fan-out (bigger pages, fewer levels: 1024 fan-out drops 1B keys to 3 levels, since 1024³ ≈ 10⁹) or caching one more level. Neither fix is a code change you make the night before a launch, which is the honest answer to "why does this delay the ship."

What I'd actually tell product: the algorithm is fine and won't get faster with more time. The delay is one week to validate depth-dependent latency at production scale and one more to tune fan-out and caching if the numbers miss. The risk of skipping it is not that search is slow in the demo; it's that it's slow only for the tail of users on the day the dataset reaches the size where the depth crosses a cache boundary.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

A teammate proposes a design that hinges on leftmost and rightmost boundaries. How do you evaluate it?

Answer

A design that hinges on leftmost and rightmost boundaries is usually a design that hinges on bisect_left and bisect_right semantics, and the evaluation starts with whether the teammate has actually pinned down which boundary the callers need.

With duplicates present, plain binary search returns an arbitrary matching index. Finding the first or last match requires a different comparison: the leftmost search treats equality as 'go left', the rightmost search treats it as 'go right', so the loop converges on a boundary rather than a member.

Python
import bisect
a = [1, 2, 2, 2, 3]
bisect.bisect_left(a, 2)    # 1 - index of the first 2
bisect.bisect_right(a, 2)   # 4 - one past the last 2
bisect.bisect_right(a, 2) - bisect.bisect_left(a, 2)  # 3 - count of 2s

Note the asymmetry: bisect_left returns the first match itself, bisect_right returns one past the last match. Off-by-one bugs at that seam are the most common defect in designs built on boundaries: range queries like 'all events in [t0, t1]' want bisect_left(a, t0) through bisect_right(a, t1), and mixing the two variants silently drops or duplicates elements at the edges. The count formula above is the same seam in miniature: it only works because bisect_right already sits one past the end of the run.

The failure mode worth naming in review: finding any match and then scanning outwards is correct but degrades to linear time when the array is largely one repeated value. A million-element array of identical values turns O(log n) into O(n). It survives casual testing because the happy path hides it; the input distribution that exposes it is exactly what a quick check leaves out.

So the evaluation comes down to three checks:

  1. Which boundary does each caller need? Leftmost, rightmost, or count (right minus left)? Returning 'an unspecified match' from a shared helper is the design smell here: name the variant in the API.
  2. Is the input actually sorted on the search key, and is that invariant maintained? Binary search's correctness guarantee is conditional on it; if the design mutates the array, the invariant needs an owner.
  3. Where do the off-by-one edges land? Half-open intervals ([lo, hi)) are the convention that keeps insertion points and slice boundaries consistent: check the design uses one convention everywhere.

If the teammate's design passes those, the boundary approach is the right one: it keeps the O(log n) guarantee regardless of duplicate density, and the boundary indices compose into range and count queries for free.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Where does insertion points matter, and where is it irrelevant?

Answer

Short answer: the insertion point only matters when the returned index is used for something other than a plain insert. Searching, counting, or maintaining an invariant. If you're only appending into a list where duplicates are acceptable, bisect_left and bisect_right give equally valid answers and the choice is irrelevant.

The mechanism, so the choice comes from the definition rather than trial: bisect_left returns the index of the first element not less than the target; bisect_right returns the index just past the last element equal to it. On a sorted list a, both are valid insertion points: inserting at either keeps the list sorted. They differ only when the target is present:

Python
import bisect
a = [1, 2, 2, 2, 3]
bisect.bisect_left(a, 2)   # 1 — index of the first 2
bisect.bisect_right(a, 2)  # 4 — one past the last 2
bisect.bisect_left(a, 9)   # 5 — both agree when the value is absent
bisect.bisect_right(a, 9)  # 5

Where it matters, when the index is a position, not just a slot:

  • First-match search: i = bisect_left(a, x); found = i < len(a) and a[i] == x gives the leftmost occurrence. Using bisect_right here and then checking a[i] == x reads the element after the run and reports not-found.
  • Counting duplicates: bisect_right(a, x) - bisect_left(a, x) is exactly the number of copies. With only one variant you'd need a scan.
  • Range queries: all values in [lo, hi) are a[bisect_left(a, lo) : bisect_right(a, hi)]. Mixing the variants silently drops or duplicates boundary values.
  • Stable insertion order: inserting equal keys into a list that must preserve arrival order (e.g. a pending-jobs queue keyed by priority) requires bisect_right, so the new element lands after its equals. bisect_left would jump the queue.

Where it's irrelevant, when any valid insertion point works:

  • Building a sorted list from unsorted input where equal elements are interchangeable (e.g. a list of plain numbers for a median calculation).
  • Using the result only as a boolean existence check done correctly (i = bisect_left(a, x) then compare a[i]), where the run's internal order doesn't matter.
  • Maintaining a multiset by insert alone, if you never rely on which copy sits where.

The failure mode this invites is specific: picking the variant by trying both until tests pass gives code that is correct until the input contains duplicates, and casual tests often use distinct values, so the bug ships. It surfaces as off-by-one reads at run boundaries: a bisect_right-based lookup that returns the element after the match, or a range query that double-counts a value sitting exactly on the boundary. The detection is a test with duplicated boundary values, which is the one case the two functions disagree on.

Versus a hand-written binary search: the library function is the right default. It's O(log n), battle-tested, and the left/right distinction is documented behavior rather than an off-by-one you own. Write your own only when you need something bisect doesn't give, like returning the element rather than the index, or a key-based search on Python versions before 3.10 added the key parameter. And note insort is O(n) per insert because it shifts the tail of the list: fine for thousands of elements, wrong for millions, where a sortedcontainers.SortedList or a heap is the honest answer.

The rule to state in the interview: decide the variant from what happens at the returned index. If something reads a[i], you need bisect_left. If something inserts at i and order among equals matters, you usually need bisect_right. If neither, duplicates impossible or interchangeable, stop thinking about it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Teach counting occurrences to an engineer who has only seen it as a rule of thumb.

Answer

Counting occurrences of a value x in a sorted array is two binary searches, not one plus a scan. The count is the gap between where x could be inserted to keep the array sorted on the left and on the right:

Python
import bisect

def count(a, x):
    return bisect.bisect_right(a, x) - bisect.bisect_left(a, x)

bisect_left returns the index of the first element >= x; bisect_right returns the index of the first element > x. Every element equal to x sits between those two indices, so the difference is the count. If x is absent, both searches return the same insertion point and the difference is 0: the absent case needs no special handling, which is worth saying out loud because most hand-rolled versions get it wrong by returning a negative span or an off-by-one.

Trace it on a concrete array. For a = [1, 2, 2, 2, 5, 7], x = 2:

  • bisect_left(a, 2) → index 1 (first position where 2 could go while staying sorted, i.e. the first 2 itself)
  • bisect_right(a, 2) → index 4 (just past the last 2)
  • count = 4 − 1 = 3 ✓

For x = 3, absent: bisect_left → 4, bisect_right → 4, count = 0. For x = 0, below every element: both return 0, count = 0. For x = 9: both return 6, count = 0.

Why not scan outwards from a hit? The intuitive version (binary-search for any occurrence, then walk left and right while elements match) is correct but linear in the number of duplicates. On an array of a million copies of the same value, the two-search version does about 2 × 20 probes; the outward scan does a million comparisons. The failure mode is quiet: casual tests use arrays with few duplicates, so the linear path never shows up, and it degrades exactly on the skewed distributions (one dominant value) where production data tends to concentrate. If you're counting over a static array repeatedly, this is also the point where you'd ask whether a Counter built once, or a precomputed index from value → range, beats per-query binary searches.

Complexity and guarantees. Both searches are O(log n) comparisons, so the count is O(log n) regardless of how many duplicates exist: that's the guarantee. What's not guaranteed is real-world latency: on an array of 64-bit ints that fits in cache, 20 probes are nanoseconds; on a cold mmap'd file or a disk-backed sorted store, each probe can be a page fault, and two searches that each touch ~20 pages may cost milliseconds. The asymptotics don't change; the constant per probe does, and that's the part you measure on the system in front of you rather than assert.

When this doesn't apply. The array must actually be sorted: the moment it isn't, both searches return garbage silently, no exception raised. If the data is unsorted or only partially ordered, you're back to a hash map (O(n) build, O(1) lookup) or a full scan. And if you only need "is it present," one bisect_left plus an equality check is enough; don't pay for the right boundary you won't use.

The one-liner to remember: count = right insertion point − left insertion point, two logarithmic probes' worth of work, zero on absence, and it only holds while the sort order holds.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

What would you ask a candidate who recites using the library implementation but cannot apply it?

Answer

The question is really about probing: the candidate knows bisect exists, so you find out whether they can use it. I'd stop asking about the library and hand them a problem where the library is the wrong shape or the right shape only after a transformation: that's where recitation breaks down.

Probe 1: apply it to a non-trivial predicate. "Given a sorted list of integers, find the first index where a[i] * 2 >= target." A candidate with a working model recognizes this is a monotone predicate over the array and reaches for bisect_left with a key:

Python
# Python 3.10+
i = bisect.bisect_left(a, target, key=lambda x: x * 2)

If they hand-roll a loop instead, fine, but I want to hear why: either they don't know key exists (a gap, not a fail), or they can articulate that the key function is called O(log n) times and that's acceptable. The reciter fails here because the problem doesn't say "binary search" anywhere; they have to recognize the structure.

Probe 2: the boundary that matters. "You have timestamps of events, sorted. How do you count events in the half-open window [t0, t1)?" This tests whether they know bisect_left from bisect_right and can say what each returns at a boundary:

Python
lo = bisect.bisect_left(ts, t0)   # first index with ts[i] >= t0
hi = bisect.bisect_left(ts, t1)   # first index with ts[i] >= t1
count = hi - lo                    # events in [t0, t1)

The follow-up that separates levels: "why bisect_left for hi and not bisect_right?" The answer (bisect_left(ts, t1) excludes events exactly at t1, which is what half-open means) is a one-sentence check that they understand the return value as an insertion point, not a magic index.

Probe 3, when the library is the wrong tool. "Find the square root of n to within 1e-6." Nothing is sorted; the monotone predicate is over the answer space, not a list. bisect doesn't apply, and the candidate has to say so and write the loop themselves:

Python
lo, hi = 0.0, max(1.0, n)
while hi - lo > 1e-6:
    mid = (lo + hi) / 2
    if mid * mid < n:
        lo = mid
    else:
        hi = mid

This is the probe I weight most. A candidate who can only recite will either force bisect onto it or flail; a candidate with the model says "binary search is a technique over any monotone predicate, bisect is just the list-specialized version" and writes the loop. That sentence is the whole distinction I'm grading.

What I'm listening for across all three:

  • They state the invariant unprompted ("everything before lo fails the predicate, everything from hi on satisfies it") rather than narrating code.
  • They know the API surface: bisect_left vs bisect_right, the key parameter (3.10+), and that insort is O(n) for the move even though the search is O(log n).
  • They can name a failure mode: off-by-one at boundaries, or using bisect_right where bisect_left was meant, which silently includes the boundary element and only breaks when a value lands exactly on it.

If they clear probes 1 and 2 but stumble on 3, that's a mid-level pass with a note. Clearing all three, with the invariant stated in their own words, is the senior signal: the library is a convenience, the technique is the knowledge.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How would you document recognising the pattern so the next owner can operate it?

Answer

The thing to document is the predicate, not the code. A successor can read a binary search loop in thirty seconds; what they cannot reconstruct is why feasible(cap) is monotone, what breaks if it isn't, and which inputs would expose that. So the documentation I'd leave behind has three artefacts.

1. A comment stating the invariant as a claim someone can falsify.

Python
# days_needed(cap) is non-increasing in cap: adding capacity never
# increases days. If a future change makes loading order matter
# (e.g. per-day weight limits), monotonicity breaks and this loop
# can return a capacity that fails the deadline — see test below.
lo, hi = max(weights), sum(weights)
while lo < hi:
    mid = (lo + hi) // 2
    if days_needed(weights, mid) <= days:   # predicate
        hi = mid
    else:
        lo = mid + 1
return lo

The comment names the assumption, the consequence of violating it, and points at the test that guards it. That last part is what makes it operational rather than decorative.

2. A property-based test on the predicate itself. The failure mode worth documenting is silent non-monotonicity: the predicate flips back and forth across the domain, the loop converges to a wrong boundary, and nothing crashes. Detection is cheap with a property test:

Python
# hypothesis: for all cap in [max(weights), sum(weights)],
# feasible(cap) implies feasible(cap + 1)
@given(st.lists(st.integers(1, 500), min_size=1, max_size=50),
       st.integers(1, 30))
def test_predicate_monotone(weights, days):
    caps = range(max(weights), sum(weights) + 1)
    flags = [days_needed(weights, c) <= days for c in caps]
    assert all(b >= a for a, b in zip(flags, flags[1:]))  # no True->False

Plus one boundary assertion per side: days_needed(weights, result) <= days and days_needed(weights, result - 1) > days. If a refactor breaks monotonicity, the property test fails with a counterexample rather than shipping a wrong answer.

3. A short runbook entry on when not to use it. Binary search over the answer space costs O(log(range) * cost(predicate)). If the predicate is expensive, say it runs a simulation, and the range is small (capacities 1..100), a linear scan of 100 evaluations may beat 7 binary-search evaluations of a 10x-costlier predicate. Conversely, if the domain is continuous or the predicate is cheap, binary search wins immediately. The runbook states the arithmetic: log2(range) * predicate_cost vs range * predicate_cost, with the actual numbers from the system, so the next owner can re-decide after a change instead of inheriting the decision.

What I'd deliberately leave out: a prose explanation of how binary search works. That's in every textbook, and restating it in a runbook just gives the successor something to skim and distrust. The valuable, non-reconstructible knowledge is the monotonicity argument (why days_needed can't increase with capacity), the guard test, and the cost arithmetic: those three, in the code and next to it, are what let someone safely modify the code a year later.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

What would you measure before treating finding the rotation point as settled?

Answer

The question is really: which parts of this are settled by correctness, and which depend on the input distribution and scale in front of me? The algorithm itself is settled, binary search against the high element finds the rotation point in O(log n), so what I'd measure before calling it done is the inputs, not the algorithm.

First, the mechanism, because it defines what assumptions I'm measuring against:

Python
lo, hi = 0, len(a) - 1
while lo < hi:
    mid = lo + (hi - lo) // 2
    if a[mid] > a[hi]: lo = mid + 1
    else: hi = mid                 # mid may be the minimum, keep it
# [1, 2, 3] -> 0; [3, 4, 5, 1, 2] -> 3

Comparing against the high end works because a[hi] is always on the minimum's side of the break; comparing against a[lo] instead fails on an unrotated array like [1, 2, 3], where it reports index 2. That's a correctness question, settled by testing, not measurement.

What I'd measure before treating it as settled:

Input distribution. How often is the array actually rotated? If 99% of inputs are unrotated or rotated by one, a linear scan that early-exits on a[i] < a[i-1] does one comparison on the common case and beats binary search's ~log₂(n) branch-heavy iterations. I'd log the rotation offset on real traffic for a week before adding the binary search at all.

Duplicates. The code above assumes distinct elements. With duplicates like [2, 2, 2, 0, 2, 2], a[mid] == a[hi] tells you nothing about which side the break is on, and the guarantee degrades from O(log n) to O(n). I'd measure whether duplicates occur in the real data; if they do, the honest answer is the worst case is linear, and the fix (hi -= 1 on the tie) costs expected performance to buy that bound.

Scale, where it matters. At n = 50, log₂(50) ≈ 6 iterations versus 50 for a scan: both are noise next to a disk or network fetch, and I'd ship whichever is simpler. At n = 10⁷ in a hot path, the difference is ~24 versus 10⁷ comparisons, and binary search wins decisively. But binary search's iterations are data-dependent branches; on a rotated array the branch predictor does poorly, so I'd benchmark rather than assume the comparison-count ratio translates to wall-clock ratio.

The test that catches the common bug. Before any of that, the unrotated input [1, 2, 3] and a single-element array go into the test suite: those are the two inputs where the low-end comparison and off-by-one bound handling break.

So: correctness is settled by proof and tests; the choice between binary search and a linear scan is settled by measured rotation frequency, duplicate rate, and n. If the interviewer's setup is a one-off in-memory array of distinct integers, I'd state the O(log n) solution, name the duplicate caveat, and move on: the measurement matters when this sits in a real pipeline with a real distribution to check.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

If last week's incident involved searching a rotated sorted array, what would you write in the report?

Answer

What the report says (first 90 seconds)

A post-incident report has four sections, and the algorithm belongs in exactly one of them. Root cause: the search decided which half of the range was sorted by comparing the midpoint to the target instead of to an endpoint. On a rotated array the array is not globally sorted, so a[mid] < target carries no information about which side the target is on. Impact: the function returned -1 for keys that were present, so every lookup that landed in the rotated tail was reported as "not found." Detection: a property test comparing the search against a linear scan over random rotations. Remediation: fix the containment test and add the cases the original tests missed.

The failing trace

The buggy version is a plain binary search:

Python
if a[mid] < target: lo = mid + 1
else:               hi = mid - 1

Run it on [4, 5, 6, 7, 0, 1, 2] looking for 0:

lohimida[mid]comparenext
06377 > 0hi = 2
02155 > 0hi = 0
00044 > 0hi = -1

Returns -1. The key is at index 4. The loop never looked right of the midpoint because the comparison assumed the array was sorted end to end.

The fix

Python
def search(a, target):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = lo + (hi - lo) // 2
        if a[mid] == target:
            return mid
        if a[lo] <= a[mid]:                  # a[lo..mid] is sorted
            if a[lo] <= target < a[mid]:
                hi = mid - 1
            else:
                lo = mid + 1
        else:                                # a[mid..hi] is sorted
            if a[mid] < target <= a[hi]:
                lo = mid + 1
            else:
                hi = mid - 1
    return -1

Trace of search([4, 5, 6, 7, 0, 1, 2], 0): mid=3, a[3]=7, a[0]=4 ≤ 7 so the left half is sorted; 0 is not in [4, 7), so lo=4. mid=5, a[5]=1, a[4]=0 ≤ 1 so the left half is sorted; 0 is in [0, 1), so hi=4. mid=4, a[4]=0 → return 4.

Alternatives the report should name

  • Linear scan, O(n): correct, no rotation logic, and the right call if the array is small or searched once. The incident happened because a log-time routine was reached for where a scan would have been fine.
  • Find the pivot (index of the minimum) with one binary search, then run two ordinary binary searches on the two sorted runs. Same O(log n), two passes, and worth it when you also need the rotation offset.
  • Duplicates: if the array can contain them, a[lo] <= a[mid] no longer identifies the sorted half. [1, 0, 1, 1, 1] searching for 0 walks off the end and returns -1 while the key sits at index 1. You must shrink the range when a[lo] == a[mid] == a[hi], which degrades the worst case to O(n).

Remediation

Fix the containment test, then add the tests that would have caught it: unrotated (k=0), fully rotated, single element, target absent, and duplicates if the input allows them. A property test (random rotation, compare against a.index(target)) covers the rest.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

How would you test a claim that the system depends on duplicates break the rotation argument?

Answer

The claim to test is: "binary search on a rotated sorted array stays O(log n) even with duplicates." I'd attack it with one adversarial input, a trace of the ambiguous branch, and a measurement. Three steps, each cheap.

Step 1: construct the witness input. The rotation argument for the distinct case rests on one invariant: at least one half of [lo, hi] around mid is always sorted, so a comparison against the endpoints tells you which side to discard. Duplicates break exactly that inference. The minimal witness is [2, 2, 2, 0, 2]:

lo=0, hi=4, mid=2: a[lo]=2, a[mid]=2, a[hi]=2

All three endpoints agree, so neither half is provably sorted: the 0 could be anywhere. The only correct move is to shrink the range by one and recurse, and that shrink is where the logarithmic bound dies.

Step 2: trace the ambiguous branch to confirm the code is correct but slow. The duplicate-tolerant version:

Python
# Python 3.12
def search(a, target):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == target:
            return mid
        if a[lo] < a[mid]:              # left half sorted
            if a[lo] <= target < a[mid]:
                hi = mid - 1
            else:
                lo = mid + 1
        elif a[lo] > a[mid]:             # right half sorted
            if a[mid] < target <= a[hi]:
                lo = mid + 1
            else:
                hi = mid - 1
        else:                            # a[lo] == a[mid], ambiguous
            lo += 1                      # safe: a[lo] != target here
    return -1

The lo += 1 is sound: a[lo] == a[mid] and a[mid] != target, so the skipped element can't be the target. Trace it on [1, 0, 1, 1, 1], target 0:

  • lo=0, hi=4, mid=2: a[2]=1 ≠ 0; a[lo]=1 == a[mid] → lo=1
  • lo=1, hi=4, mid=2: a[2]=1 ≠ 0; a[1]=0 < a[2]=1 → left half sorted; 0 <= 0 < 1 → hi=1
  • lo=1, hi=1, mid=1: a[1]=0 → return 1

Correct, and the shrink only cost one step here. The test suite still needs the cases where the ambiguous branch fires repeatedly: the all-equal array ([2,2,2,2], target absent), the one-distinct array ([2,2,2,0,2]), and the target sitting at each end of a long duplicate run. Correctness tests alone won't expose the complexity claim, though: that's step 3.

Step 3: measure the degradation. Instrument the loop:

Python
count = 0
# inside the while loop:
count += 1

Run on [1] * n + [0] for n = 2^12, 2^14, 2^16. While lo < n, every probe lands on a 1, a[lo] == a[mid] fires, and lo advances by exactly one per iteration, so the count grows as ~n, not ~log n. The same instrument on a distinct-valued rotated array shows ~log₂(n) iterations (12, 14, 16). One table, claim dead: the bound is Θ(n) worst case with duplicates, Θ(log n) without.

The trade-off. If the input is known distinct (IDs, timestamps) the ambiguous branch is dead code and the O(log n) claim holds; I'd assert distinctness as a precondition rather than pay for it. If duplicates are possible but rare, the amortized cost is fine and I'd keep the shrink-by-one branch with a comment naming the worst case. If an adversary controls the input (a cache key that can be flooded with one value), the duplicate-tolerant search is a DoS vector and I'd switch to a linear scan or sort-once-then-bisect. The deciding question is who controls the value distribution, not the algorithm.

So: witness input, trace of the ambiguous branch, instrumented scaling run. Each step takes minutes, and together they test the claim rather than the slogan attached to it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

How would you review a pull request whose risk is searching a two-dimensional sorted matrix?

Answer

Reviewing this PR, the first thing I'd pin down is which sortedness invariant the code actually relies on, because "sorted 2D matrix" is ambiguous and the right algorithm depends on it. Row-and-column sorted (each row sorted left-to-right, each column top-to-bottom) supports a staircase walk in O(rows + cols); fully sorted in row-major order supports a single binary search in O(log(rows × cols)). If the PR assumes one and the data provides the other, it's either wrong or needlessly slow, so I'd check the invariant is documented and, ideally, asserted.

For the row-and-column case, the code I'd expect to see starts at a corner:

Python
r, c = 0, len(m[0]) - 1            # top-right
while r < len(m) and c >= 0:
    if m[r][c] == target: return True
    if m[r][c] > target: c -= 1    # this column can't contain it
    else: r += 1                   # this row can't contain it
return False

The mechanism: from the top-right, the current cell is the largest value in its row and the smallest in its column. Too big, nothing below in that column can match, so drop the column; too small, nothing left in that row can match, so drop the row. Every step eliminates a full row or column, giving O(rows + cols). I'd want the PR comment to say why the corner works, not just "standard technique", if the author can't justify the invariant, they won't catch it breaking.

What I'd flag in review:

  • Per-row binary search (for row in m: bisect(row, target)): correct, but O(rows · log cols). On a tall matrix, 100k rows × 4 cols, that's ~200k comparisons against the walk's ~100k. Worth a comment, not a block, unless the matrix is known to be tall.
  • Starting at the wrong corner. Top-left and bottom-right are the dead corners: from top-left, a too-large target could be anywhere to the right or below, and you eliminate nothing. This is the most common bug and it still passes many tests, because the walk often finds targets that happen to lie on its path.
  • Missing edge cases in tests: empty matrix, empty rows, single element, target smaller than the minimum or larger than the maximum. The walk handles all of these, but only if the loop bounds are right: c >= 0 and r < len(m) are exactly what the tests should be exercising.
  • Assuming sortedness without checking it. If the matrix comes from a database query or another service, the invariant is a contract, not a fact. I'd ask the author where the data comes from and whether a debug-mode assertion or a comment naming the producer is warranted.

Questions I'd leave as PR comments rather than blocking on: is this on a hot path (does the log factor matter at real sizes), and is the matrix ever fully row-major sorted. In which case flattening the index math (m[i // cols][i % cols]) and doing one binary search is both simpler and faster.

The one thing I'd insist on changing: any code whose correctness depends on the sortedness invariant must state that invariant where it's used. The staircase walk is three lines; the review value is almost entirely in making the precondition visible so the next reader doesn't reuse it on data that doesn't satisfy it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

What is the smallest experiment that would change your mind about searching over an implicit array?

Answer

The smallest experiment is two timings and one comparison. You don't benchmark the search: you time the two primitives it is built from, one probe and one bulk fetch of the same range, and compare probe_cost × log2(N) against bulk_cost. A search over an implicit array costs exactly log2(N) probes, so those two unit costs decide it. That is why you never have to run the search to settle the question.

Python
import time

def probe(i):          # one round trip
    return fetch_row(i)

def bulk(lo, hi):      # one round trip for the whole range
    return fetch_range(lo, hi)

N = 1_000_000
t = time.perf_counter(); probe(N // 2); probe_ms = (time.perf_counter() - t) * 1000
t = time.perf_counter(); bulk(0, N);    bulk_ms  = (time.perf_counter() - t) * 1000

print(probe_ms, bulk_ms, probe_ms * 20 > bulk_ms)

log2(1_000_000) ≈ 20, so the search pays 20 probes. With a hypothetical 40 ms probe and a 300 ms bulk fetch the last line prints 40.0 300.0 True: 20 × 40 = 800 ms of probing loses to one 300 ms fetch, and you materialise. Swap in a 2 µs in-process probe and it prints 0.002 300.0 False: 40 µs of probing beats the fetch, and the implicit search stays.

That flip is the whole point. The experiment changes your mind when the inequality changes sign, and the sign depends on both numbers, so both have to be measured on the real system with the real N.

What makes the experiment lie to you:

  • A warm cache or a localhost stub. The probe looks cheap, you keep the implicit search, and it collapses the first time the backend is cold or remote. Measure against the real backend.
  • Counting only latency. A bulk fetch of 1M rows may be 300 ms and 200 MB; the comparison is latency against latency plus memory, and the memory side can be the one that decides.
  • Assuming the probes are independent. Sequential probes each pay full round-trip latency; if you can pipeline them, the arithmetic changes and the crossover moves.

When not to run it: if the probe is an in-process array access, the answer is obvious, 20 array reads are free next to any fetch, and the experiment is a formality.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How would you reason about the monotonic-predicate formulation in a system you own?

Answer

When I hear "binary search," I don't think sorted arrays: I think: a predicate over some parameter that is false for a prefix of the domain and true for the rest. The search finds the boundary. A sorted array is just the special case where the predicate is a[i] >= target.

In a system I own, this shows up as answer-space search: nothing in memory is sorted; the predicate supplies the order. Three places it's bitten me or nearly did:

  • Connection pool sizing. Predicate: "a pool of N connections keeps p99 request latency under 100 ms at peak load." Too small is infeasible (queueing), big enough is feasible. Monotone up to a point, but see the failure mode below.
  • Autoscaling thresholds. Predicate: "with a scale-out threshold of X ms average CPU, we stay within our SLO during a 30-minute traffic spike replay."
  • Timeout tuning. Predicate: "a downstream timeout of T ms keeps the downstream error rate under 0.1% while not exceeding our retry budget."

The skeleton is always the same:

Python
def feasible(capacity): ...        # False, False, ..., False, True, True, ...
lo, hi = 1, max_capacity
while lo < hi:
    mid = lo + (hi - lo) // 2
    if feasible(mid): hi = mid
    else: lo = mid + 1
return lo                          # smallest feasible capacity

With lo=1, hi=64, that's ceil(log2(64)) = 6 evaluations of feasible. That count is the whole cost model: if each evaluation is a 20-minute load test, the search costs ~2 hours; if it's a 50 ms simulation against a recorded trace, it costs 300 ms. The technique's value is entirely a function of how expensive one predicate evaluation is.

Before searching, I prove monotonicity, and I mean prove, not assume. The classic trap: pool sizing is not monotone at the top. A pool of 200 connections against a Postgres instance tuned for 100 backends is worse than 100: lock contention, context switching, memory pressure. The predicate goes false–true–false. Binary search will happily return a boundary in the middle region and never notice the second flip. Detection: evaluate the predicate at the returned boundary and at a point well above it; if the high end is infeasible, the domain isn't a two-region predicate and I fall back to a scan or shrink hi to the point where the flip is proven single.

The other failure mode is a noisy predicate: feasible measured from a live load test has variance. If p99 latency at capacity 40 is 95 ms ± 15 ms run to run, the boundary region flips randomly and the search converges to noise. Detection: evaluate the same mid twice; disagreement means the predicate isn't deterministic enough. Fixes: fix the seed and replay a recorded traffic trace instead of generating load, widen the pass threshold to a band, or evaluate each point with enough samples that the confidence interval is smaller than the gap between adjacent capacities.

Off-by-one at the boundary is the mechanical failure: hi = mid vs hi = mid - 1, or returning lo when the loop exits with lo == hi but never checking whether the final point was ever evaluated. The loop above is the invariant-safe form: hi only ever moves to a known-feasible value, lo only to a known-infeasible one plus one, and I'd rather memorise one correct template than re-derive the boundary conditions under interview pressure.

When it's the wrong tool:

AlternativeWhen it wins
Linear scan over the domainDomain is small (say 20 candidate pool sizes) or predicate evaluations are nearly free: the log-factor buys nothing and the code is simpler
Ternary searchPredicate is unimodal but not two-region: you're minimising a cost, not finding a feasibility boundary
Sampling + interpolationPredicate evaluations are very expensive (multi-hour soak tests); 4–5 well-spread samples plus a model of the curve often beats 6 blind bisection points
Analytic modelIf queueing theory gives you a closed-form answer (M/M/c: capacity from target utilization ρ ≈ 0.7), search only to validate, not to discover

The senior-level point: correctness here is a property of the system, not of the algorithm. The algorithm is proven; the monotonicity of feasible is an assumption about how my service behaves under load, and it's exactly the kind of assumption that holds in the test environment and breaks in production. So I state the predicate explicitly, argue monotonicity from the system's mechanics (queueing is monotone in capacity; contention is not), verify the boundary empirically, and make the assumption visible in the design doc so the next person knows what to re-check when the system changes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

A vendor promises choosing the answer range is handled for you. What do you still own?

Answer

Assume the question means binary search on the answer: a vendor library or framework offers to pick the search range for you, and the question is what remains your responsibility. What you still own is the correctness proof of the bounds, because the search's contract only holds if the predicate is monotone across the range and the endpoints bracket the true answer: the low bound must be infeasible (or trivially minimal) and the high bound must be feasible. No library can check that for you, because feasibility depends on the problem's semantics, not the search mechanics.

Why the high bound specifically: binary search on the answer converges to the smallest value in [lo, hi] for which the predicate succeeds. If hi itself is infeasible and every value below it fails too, the search returns hi anyway: an answer no check ever validated. It is silently wrong, not loudly wrong, which is the worst kind of failure. A lo that is too high is less dangerous but still wrong: it can skip past the true answer if the predicate isn't actually monotone down there.

Concretely, for the split-weights problem (split an array into k contiguous groups minimising the largest group sum: the same shape as shipping packages in k days):

Python
lo = max(weights)   # any smaller capacity can't hold the heaviest item: infeasible
hi = sum(weights)   # one group carries everything: certainly feasible

Both bounds come from the problem's constraints, not from a round number. hi = 10_000 because it "looks big" returns 10,000 unchecked the first time the true answer exceeds it, and that input is exactly the one casual testing leaves out, because it only appears at the scale or distribution the quick checks skipped.

Trade-offs worth naming:

  • Tighter bounds. lo = max(max(weights), ceil(sum(weights) / k)), the average is also infeasible-or-minimal for k groups, cuts the search range and with it the iterations. Worth it when the feasibility check is expensive; the correctness argument is identical.
  • Parametric search vs. DP. Binary search on the answer needs a feasibility check that runs in O(n) per candidate, giving O(n log(sum)) total. A DP over prefixes gives the exact answer in O(n²k) or better with monotonicity tricks. Search wins when n is large and the check is cheap; DP wins when the predicate isn't monotone (then binary search is simply wrong, not just slower) or when you need the actual split, not just the value.
  • What you assert vs. what you measure. Feasibility of hi is provable from the constraints: assert it in a test with the extreme input. Whether the check itself is fast enough at scale is not provable; that you measure.

The failure mode to name in an interview: a vendor-supplied range is a default, not a guarantee. If the library picks hi = some_constant or derives it from a different assumption than your problem makes, the search still terminates and still returns a number: it just isn't the answer. Detection is cheap: a test at the constraint extremes (one huge item, all items equal, k = 1, k = n) plus an assertion that the returned value actually passes the feasibility check. That last assertion is the one thing that converts a silent wrong answer into a loud one, and it is yours to write regardless of who picked the range.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

How does binary search on the answer change if the workload grows by two orders of magnitude?

Answer

Short answer

"Workload" could mean three different things here, and they cost wildly different amounts. Binary search on the answer costs

passes × cost-per-check, where passes ≈ log2(hi − lo) ≈ log2(sum(weights))

  • 100x more items, same weight distribution. hi = sum(weights) grows 100x, so passes go from ~20 to ~27. Each check now streams 100x the data. Total ≈ 135x, and worse in wall clock, because the array stops fitting in cache.
  • 100x bigger numbers, same n. sum also grows 100x, so passes again go 20 → 27, but the check still walks the same n elements. Total ≈ 1.35x. The magnitude of the answer barely matters; the pass count is logarithmic in it.
  • 100x more expensive check (it became a remote call, or O(n log n)). Passes unchanged, total 100x.

So the log factor is the cheap part, and it is the part people quote. At 100x, the check is the bill.

What grew 100xPassesCost per checkTotal
n (same weight distribution)20 → 27100x elements~135x
Every weight (n fixed)20 → 27unchanged~1.35x
Cost of one check20100x100x

The check itself

Python
def days_needed(weights, cap):          # O(n)
    days, load = 1, 0
    for w in weights:
        if load + w > cap:
            days += 1
            load = 0
        load += w
    return days

On weights = [3,2,2,4,1,4], cap = 6: loads go 3, 5, then 2 (day 2), 6, then 1 (day 3), 5 → returns 3.

What actually breaks at 100x

  1. The upper bound overflows. hi = sum(weights) with n = 1e8 and weights up to 1e4 is 1e12, which wraps a 32-bit int. In C++ or Java the loop then runs on a negative bound and returns garbage. Assert hi >= lo and hi >= max(weights) before the loop; sum in int64.
  2. Cache. At n = 1e6 an int32 array is 4 MB and stays in L3; each pass is a fast streaming scan. At n = 1e8 it is 400 MB and every pass is DRAM-bound. Per-element cost rises several-fold on top of the 100x element count, so wall clock grows faster than the element count. (Illustrative, machine-dependent: ~0.1 ns/element L3-resident vs ~0.4 ns/element DRAM-bound.)
  3. The check is sequential. days_needed carries load across iterations, so you cannot throw cores at it. If the search is too slow at 100x, parallelism on the check is not available to you.

The alternative that changes the cost model

If the number of days D is small relative to n, replace the O(n) check with an O(D log n) one over prefix sums: from position i, binary-search the largest j with P[j] - P[i] <= cap, jump to j, repeat. With n = 1e8 and D = 1000 that is 1000 × 27 ≈ 27k operations per check instead of 1e8. Use it when D·log n < n; it loses to the linear scan as D approaches n.

Linear scan over candidate answers is O(R · C) and only wins when the range is tiny. If the check is a remote call, batch or memoize it rather than adding passes.

How to tell which regime you are in

Instrument the check: count invocations and time one call. If passes × time-per-check blows the budget, fix the check. If passes alone is the problem, tighten lo and hi with a cheap bound before searching.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

When would you refuse a design because of binary search on floating-point ranges?

Answer

Refuse the design when its correctness depends on a property IEEE-754 floats don't provide. Three triggers, in the order I'd raise them in review.

1. Termination is while lo < hi, with no iteration cap and no tolerance. That loop can hang, so it's a bug, not a style preference. Refuse.

2. The predicate isn't provably monotone over the float domain. Binary search's invariant is that feasible is true on a prefix of the domain and false after it. Rounding, FMA contraction (compiler- and flag-dependent), and libm transcendentals, which the C standard does not require to be monotone, can flip the predicate at adjacent floats near the boundary. If the design assumes monotonicity with no guard band and no exact-arithmetic fallback, refuse.

3. The spec is unsatisfiable. A required tolerance below the ULP of the answer's magnitude, or a relative tolerance on a range that spans zero, cannot be met by any float search. Refuse and change the spec.

Everything else is a design you can fix rather than reject.

Why the hang is real. Take lo = 1.0, hi = nextafter(1.0, 2.0) = 1.0 + 2^-52. Then lo + hi = 2.0 + 2^-52, exactly halfway between 2.0 and 2.0 + 2^-51; ties-to-even rounds it to 2.0, so mid = 1.0 = lo. With the invariant feasible(lo) true, the branch sets lo = mid, which is lo unchanged: the loop spins forever. The interval is already one ULP wide; no float lies strictly between the bounds.

Fixed count vs tolerance. Both are legitimate; they fail differently.

Fixed iteration countAbsolute + relative tolerance
Runtimedeterministic, ceil(log2(range/tol))data-dependent
Fails whenrange or target changes at runtimerange spans zero (relative term degenerates), or tolerance < ULP (never terminates)
Costmay waste iterations past ULPmay run long on a hard instance

The deciding criterion is the predicate's cost. Cheap predicate, known range: fixed count, capped at 53 for double. Beyond that the interval is at ULP and iterations do nothing. Expensive predicate (a simulation, a solver): compute the minimum count from the range and target; don't guess 100.

Failure modes and how to detect them.

  • Hang at ULP. Detect with an iteration-counter assertion, or a post-loop check that lo and hi are adjacent floats.
  • Non-monotone predicate. Binary search returns a point that isn't the boundary. Detect by asserting feasible(lo) && !feasible(hi) after the loop; if it fails, the predicate isn't monotone.
  • Relative tolerance near zero. Detect by asserting the range doesn't straddle zero, or by using an absolute floor.
  • Cross-platform divergence. Same source, different result under FMA contraction or -ffast-math. Detect with golden-value tests per target.

ULP vs magnitude (double), the ceiling on any tolerance:

magnitudeULP
1.02^-52 ≈ 2.2e-16
1e32^-43 ≈ 1.1e-13
1e62^-33 ≈ 1.2e-10
1e92^-23 ≈ 1.2e-7

A search over [0, 1e9] reaches ULP in ceil(log2(1e9 / 1.2e-7)) ≈ 53 iterations; a 100-iteration loop spends the last 47 doing nothing. If the spec asks for 1e-9 absolute on a value near 1e9, refuse: that's below the representable spacing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

What failure would you inject to check a team's understanding of when sorting first is not worth it?

Answer

The failure I'd inject: a hot path that sorts a collection on every request before doing a single binary search into it. It's the cleanest probe because the code looks idiomatic (sort, then bisect) and the bug is invisible at small scale, so a team that understands amortization catches it and a team that memorized "binary search is O(log n)" does not.

Concretely, take a service that answers point lookups against a reference dataset. The wrong version:

Python
# Called once per request; data is ~1M rows and effectively static
def lookup(data, key):
    data.sort()                      # O(n log n) per request
    i = bisect.bisect_left(data, key)
    return data[i] if i < len(data) and data[i] == key else None

The right version sorts once at load time and probes per request:

Python
data.sort()                          # once, at startup
def lookup(data, key):                # O(log n) per request
    i = bisect.bisect_left(data, key)
    return data[i] if i < len(data) and data[i] == key else None

The arithmetic that decides it: with n = 1,000,000, a sort is roughly n log₂ n ≈ 20 million comparisons per request. A linear scan is n ≈ 1 million comparisons and needs no sort. So for a single lookup, the "fast" version does about 20× the work of the naive scan it replaced: the sort never pays for itself even once, let alone amortizes. Only when the same sorted order serves many queries does the 20M-comparison cost get divided down; with 1,000 queries against the same data, the sort-once version spends 20M + 1,000·20 ≈ 20M comparisons total versus 20 billion for sort-per-query. That crossover, how many queries share one sort before it wins, is exactly the understanding the injected failure tests.

What makes it a good probe rather than a gotcha:

  • It survives casual testing. At n = 1,000 the per-request sort costs maybe 100 µs; nothing looks wrong in a unit test or a demo. The failure only appears under production-shaped load, which checks whether the team reasons about scale or just about Big-O labels.
  • It has a second right answer. If the only operation is point lookup and order is never needed, a hash set or dict is better than sorting at all: expected O(1) per lookup with no ordering cost and no sorted-invariant to maintain. A team that reflexively answers "sort once outside the loop" without asking "do you need order at all?" has half the model.
  • It exposes the maintenance failure mode too. Once data is sorted outside the loop, every mutation has to preserve the invariant: an append that breaks sortedness makes bisect silently return wrong answers, not errors. That's the follow-up I'd listen for: the fix isn't free, it moves the cost from runtime to correctness discipline.

How I'd run it: hand the team the wrong version in review, or inject it into a load test against a staging service and show p99 before and after. The detection signal is characteristic: latency scales with dataset size per request rather than with query volume, and a CPU profile shows the sort dominating while bisect is a rounding error.

What I'd want to hear back, in order: the single-lookup case is cheaper as a scan; the many-lookup case sorts once outside the loop; the point-lookup-only case uses a hash structure; and the sorted-once design now owns an invariant that mutations must respect. If the discussion lands there, the team has the trade-off, not the slogan.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

What belongs in a runbook section on cache behaviour and interpolation search, and what does not?

Answer

Assume the runbook serves engineers tuning a lookup-heavy service: sorted arrays of millions of keys, latency SLOs, on-call debugging. The question is really: what does an on-call engineer need to decide or verify about cache behaviour and interpolation search at 3 a.m., versus what belongs in a design doc?

What belongs:

  1. The measured latency profile, not the asymptotics. Binary search on an 8 MB array (1M × 8-byte keys, well past a typical 512 KB–2 MB per-core L2) does ~20 probes, each a likely cache miss with a dependent load chain the prefetcher can't help. A runbook entry should carry the actual numbers from this system: e.g. "p99 lookup = 180 ns warm, 900 ns cold, measured 2024-06 on the prod hardware profile." Those figures are what an on-call comparison against current metrics uses.

  2. Interpolation search's applicability condition, stated as a checkable predicate. Interpolation search is O(log log n) only when keys are roughly uniformly distributed over their range; on skewed or clustered data it degrades to O(n): worse than binary search's guaranteed O(log n). The runbook should say how to verify the precondition on this dataset (plot key distribution, or compute the empirical ratio of (max − min) / n against actual spread), and what the fallback is when it fails.

  3. The decision rule for when each applies:

Binary searchInterpolation search
Comparisons (uniform keys)O(log n), ~20 for 1MO(log log n), ~4–5 for 1M
Worst caseO(log n) guaranteedO(n) on skewed data
Cache behaviour~20 scattered dependent missesFewer probes on uniform data (~4–5 misses instead of ~20); same scattered dependent-miss pattern per probe, no prefetch advantage
When to useDefault; unknown/adversarial distributionsLarge arrays, verified-uniform keys, read-heavy

The cache win from interpolation search is purely fewer misses, not friendlier ones: each probe is still a dependent load the hardware cannot prefetch, and on non-uniform data the probe count can exceed binary search's.

  1. Failure modes with detection: a latency regression that tracks a data reload (distribution changed → interpolation degraded silently); p99 spiking only on cold cache after a deploy reshuffles memory layout. Each entry names the metric and threshold that trips it.

What does not belong:

  • Derivations of why interpolation is O(log log n): that's interview material, not incident response.
  • Unqualified claims like "interpolation search is faster." Without the distribution caveat it's the exact mistake the runbook exists to prevent.
  • Generic advice ("measure, don't assume") without the specific measurement, its date, and the hardware it was taken on.
  • Alternatives not actually available in this codebase (B-trees, Eytzinger layout) unless someone has benchmarked them here; naming them without numbers just adds noise to a page someone reads under pressure.

The one-sentence version: the runbook carries measured numbers, the applicability predicate for interpolation search, and the failure signatures. Everything else is design-doc content.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

How does off-by-one testing strategy interact with rollback, and where do people ignore that?

Answer

Core answer. Rollback code is boundary-heavy: checkpoints are indices, batches have a partial final chunk, and triggers compare against a threshold. Off-by-one testing strategy, sweeping every small size rather than picking one, is what catches those bugs. People ignore the interaction because they test rollback at a size that divides evenly by the batch and assert only that it ran.

Why rollback is boundary-heavy. A checkpoint is an index, and the first decision is whether it names the last committed row or the first uncommitted one: inclusive or exclusive. Get it wrong and you drop or keep exactly one row. A batch loop has a partial final batch whenever len(rows) % batch != 0, so the last chunk is a different shape from every other chunk. A rollback trigger compares a metric to a threshold, and > versus >= decides whether a run sitting exactly at the threshold rolls back.

Worked example. A runner applies rows in batches and checkpoints only when a batch is full; rollback truncates to the checkpoint.

Python
def apply_batches(rows, batch=3):
    applied, last_committed = [], -1
    for start in range(0, len(rows), batch):
        chunk = rows[start:start + batch]
        applied.extend(chunk)
        if len(chunk) == batch:
            last_committed = start + len(chunk) - 1
    return applied, last_committed

def rollback(applied, last_committed):
    return applied[:last_committed + 1]

Trace rows = list(range(7)), batch=3:

  • start=0: chunk [0,1,2], full, last_committed=2, applied [0,1,2]
  • start=3: chunk [3,4,5], full, last_committed=5, applied [0,1,2,3,4,5]
  • start=6: chunk [6], not full, last_committed stays 5, applied [0,1,2,3,4,5,6]

rollback(applied, 5) returns applied[:6] = [0,1,2,3,4,5]. Row 6 was applied but never checkpointed, so rollback drops it.

The sweep that catches it.

Python
for n in range(0, 11):
    for batch in range(1, 5):
        rows = list(range(n))
        applied, lc = apply_batches(rows, batch)
        assert rollback(applied, lc) == rows

Fails first at n=1, batch=2: chunk [0] is not full, last_committed stays -1, rollback returns applied[:0] = [], which is not [0]. A hand-picked test at n=6, batch=3 passes: both batches are full, last_committed=5, rollback returns applied[:6] = [0,1,2,3,4,5] = rows. The round size hides the bug because there is no partial final batch.

Where people ignore it. No failure is injected, so rollback only runs on the happy path and the partial batch never appears. The test size is a multiple of the batch size. The assertion is "rollback ran" rather than "the surviving set is exactly the committed set." And rollback is tested against a hand-built state that doesn't match what the runner produces.

Choosing a strategy. An exhaustive small-size sweep is cheap, complete for small state, and needs a brute-force oracle: use it for the runner and rollback pair. Property-based testing covers large inputs but needs an invariant you can state and is slower to debug when it fails. Hand-picked cases are fastest and only as good as the sizes you chose, and the sizes people choose are the round ones.

Failure modes and detection. Rollback drops the last committed row (inclusive/exclusive): assert the post-rollback set equals the committed set. Rollback drops a partially applied final batch because the checkpoint only advances on a full batch: assert no row from the failed batch survives. A > versus >= trigger never fires at exactly the threshold: test the exact boundary value.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How should on-call treat an alert that names binary search versus hashing as the cause?

Answer

An alert that names a data-structure choice as the cause is already suspect, and that's the first thing to say out loud. Alerts should fire on symptoms (latency, error rate, saturation) not on design decisions. Binary search versus hashing isn't something a monitor can observe; it's a hypothesis someone embedded in the alert. So on-call treats it as a hypothesis to falsify, not a diagnosis to act on.

Concretely, the first 15 minutes go to the symptom, not the theory:

  1. What is the alert actually measuring? If it's a p99 latency threshold, pull the latency distribution and the request logs. If it's a synthetic check timing out, find which endpoint.
  2. When did it start, and what shipped? A latency regression that coincides with a deploy is far more likely to be the deploy than a long-standing O(log n) vs O(1) difference: those costs were there yesterday too.
  3. Reproduce the slow path with the production data shape, not a sample of 100 rows.

The hypothesis is still worth taking seriously, because it's a real failure mode. The classic version: a service was built on a hash-based structure (set/dict in Python, HashSet in Java) and later grew ordered queries (predecessor, successor, range) which the hash can't answer without a full scan:

Querysetsorted list + bisect
x present?O(1) expectedO(log n)
smallest element > xO(n) scanO(log n)
range [lo, hi)O(n) scanO(log n + k)
ordered iterationnot supportedfree

If the alert's latency spike lines up with a code path doing min(s for s in items if s > x) or an equivalent scan, and that path's traffic grew, the hypothesis is confirmed, and the fix is a sorted structure (or a tree like a B-tree/skip list if you need concurrent inserts), not tuning the hash. If profiling shows the slow path is a point lookup that got slower, the hash-versus-search framing is a red herring and you look elsewhere: pool saturation, cache misses from a cold restart, a downstream dependency.

What on-call should not do is page a rewrite. Swapping the structure is a code change with its own risks (rehashing cost, memory doubling if you keep both during migration) and it doesn't belong in an incident response. The incident-time action is mitigation: shed or batch the ordered-query traffic, raise a cache in front of the scan, or roll back the change that added the query. The structural fix is a follow-up with a load test behind it.

The one-line version for the interviewer: an alert naming a cause has smuggled a diagnosis past you. Verify the symptom, time-correlate it with deploys, profile the hot path, and only then decide whether the data-structure hypothesis survives.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

What trade-off does the median of two sorted arrays force that a junior answer usually skips?

Answer

The trade-off the question is really about: you can get a correct answer in O(m+n) with a merge so simple it cannot be wrong, or O(log(min(m,n))) with a partition search whose correctness lives entirely in boundary conditions. The binary-search version buys ~10 probes instead of ~1,000 comparisons on a 1,000-element array, and pays for it with the two bug classes below. A junior answer recites the complexity; it never says what the complexity costs you in correctness surface area.

The two sides, concretely. Merge: walk both arrays with two indices, take the smaller head each step, stop once you've consumed ceil((m+n)/2) elements. For an odd total that lands you on the median, for an even total you need one more element to average. About 15 lines, no edge cases beyond loop bounds. Partition search: binary-search a cut i in the shorter array A; the cut in B is forced to j = (m+n+1)//2 - i so the left halves together hold ceil((m+n)/2) elements. One more than half when the total is odd, which is what makes the odd case's median (a single left-side element) fall out of the same formula. The cut is valid when A[i-1] <= B[j] and B[j-1] <= A[i]: that predicate is monotone in i, which is why binary search applies at all.

Python
# a is the shorter array; i elements of a on the left
i = (lo + hi) // 2
j = (m + n + 1) // 2 - i          # left halves total ceil((m+n)/2)
left_a  = a[i-1] if i > 0 else float("-inf")
right_a = a[i]   if i < m else float("inf")
left_b  = b[j-1] if j > 0 else float("-inf")
right_b = b[j]   if j < n else float("inf")
# valid iff left_a <= right_b and left_b <= right_a

Where the fast version actually breaks. Two named bugs, both found in review, not by happy-path tests:

  1. Searching the longer array. Then j = (m+n+1)//2 - i can go negative or past len(B), and the sentinel guards don't cover it. Fix: swap so you always cut the shorter one. Detection: a test with len(a)=1, len(b)=1000.
  2. Odd/even total-length handling. With an odd total, the median is max(left_a, left_b); with an even total it's (max(left_a, left_b) + min(right_a, right_b)) / 2. The +1 in (m+n+1)//2 is what makes the odd case work: with an odd total it puts the extra element on the left so max(left_a, left_b) is the median. Get it wrong and odd totals return the wrong element. Detection: parametrized tests over total lengths 1..6 across both parities of the split.

Plus the classic off-by-one: hi should start at m, not m-1, because a valid cut can put all of A on the left half.

When to take the slow side anyway. If this runs once on arrays that fit in memory, the merge is the right call: the 10x-to-100x probe saving is irrelevant against the cost of the partition bugs reaching production. Take the partition search when the input is large enough that the merge is measurable (say, streaming two multi-gigabyte sorted runs where you'd also avoid materializing the merge), or when it's a hot path called per-request. In an interview, say both: give the O(log) answer, then name the merge as the version you'd actually ship for a one-off, and why.

Curated: · Written: · Reviewed:

Difficulty: Hard