Skip to content
Tech Interview Prep
Technical interview guide

Intervals

Ranges with a start and end: sorting by start (or end) turns overlap and merge problems into a single linear pass.

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

Scope: Language-neutral, with sorting and heap behaviour cited from CPython 3.14.

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-4

What does merging overlapping intervals guarantee, and what does it deliberately leave open?

Answer

The guarantee. Merging overlapping intervals returns a canonical form: the intervals come out sorted by start, pairwise disjoint, and their union equals the union of the input. It is also minimal, no two output intervals can be combined without changing the union, and idempotent: merging the result again returns it unchanged. That is the whole contract. Everything else is a choice the merge does not make for you.

Why minimal and unique. For closed intervals the union of any family is itself a union of maximal intervals, and that decomposition is unique. Merging just computes it. The mechanism is one left-to-right pass over the input sorted by start: hold the current interval, and when the next one starts at or before the current end, extend the current end to the larger of the two; otherwise emit and start fresh.

Python
def merge(intervals):          # closed intervals [s, e], s <= e
    out = []
    for s, e in sorted(intervals):
        if out and s <= out[-1][1]:
            out[-1][1] = max(out[-1][1], e)
        else:
            out.append([s, e])
    return out

Trace on [(1,10),(2,3),(5,12),(20,21)]:

stepintervalout beforeaction
1(1,10)[]append → [[1,10]]
2(2,3)[[1,10]]2 ≤ 10, end = max(10,3) = 10 → [[1,10]]
3(5,12)[[1,10]]5 ≤ 10, end = max(10,12) = 12 → [[1,12]]
4(20,21)[[1,12]]20 > 12, append → [[1,12],[20,21]]

Result [[1,12],[20,21]]. Feeding that back in returns the same list: idempotence.

What it leaves open.

  • Boundary convention. Whether touching intervals merge is not decided by the merge; it is decided by whether your intervals are closed or half-open. [1,2] and [2,3] share the point 2 and merge to [1,3]; [1,2) and [2,3) do not touch and stay separate. The only change is s <= out[-1][1] versus s < out[-1][1]. Pick the one that matches your data and say which.
  • Provenance. A merged interval does not record which inputs produced it. If you need to map back (which meetings, which IP ranges, which orders) carry a payload list alongside the bounds.
  • Output order. Sorted by start is a choice, not a consequence of merging. If a caller needs input order, you must restore it.
  • Cost. The guarantee is about the result, not the algorithm. Sorting dominates at O(n log n); a sweep over already-sorted input is O(n).

Failure modes. Using < on closed intervals leaves exactly-touching intervals unmerged: a zero-width gap that is really a shared point; a test with [1,2],[2,3] catches it. Assigning e instead of max(out[-1][1], e) shrinks the range under containment: [(1,10),(2,3)] becomes [(1,3)], silently dropping (3,10]. Skipping the sort misses merges that only appear once the input is ordered.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-1

Explain half-open interval conventions and how it changes a production decision.

Answer

Core answer

The convention decides whether an event landing exactly on a boundary is counted once or twice. Use half-open [start, end) for anything that partitions a continuous domain (time buckets, offset ranges, pagination cursors, shard key ranges) because adjacent intervals then tile without overlap and length = end - start needs no correction. Use closed [start, end] when the domain is discrete and the range is user-facing: calendar dates, "pages 1–10", SQL BETWEEN, HTTP byte ranges.

The production decision this changes most often is the aggregation window in a metrics or billing pipeline.

The mechanism, with numbers

A counter emits one sample per second. You roll up into 60-second buckets and sum.

Half-open buckets [0,60), [60,120), … over samples t = 0…3599: 60 buckets × 60 samples = 3600. Every sample lands in exactly one bucket.

Closed buckets [0,60], [60,120], …: the sample at t = 60 satisfies both 0 ≤ 60 ≤ 60 and 60 ≤ 60 ≤ 120. Every interior boundary (t = 60, 120, …, 3540, which is 59 values) is counted twice. Total 3659 instead of 3600, a 1.6% inflation that grows as the bucket width shrinks relative to the sample rate.

Python
# Python 3.12
def bucket(ts, width=60):
    return ts // width          # half-open: [0,60) -> 0, [60,120) -> 1

bucket(0), bucket(59), bucket(60), bucket(119), bucket(120)
# (0, 0, 1, 1, 2)

ts // width is the whole implementation. The closed version needs a comparison against both ends plus a tie-break rule for the boundary, and the tie-break is where the double count comes from.

Where the convention is already fixed for you

SurfaceConventionBoundary behaviour
Python range(a,b), s[a:b]half-openb excluded
Java substring(a,b), List.subListhalf-openb excluded
Go s[a:b]half-openb excluded
SQL BETWEEN a AND bclosedboth included
SQL idiom >= a AND < bhalf-open
HTTP Range: bytes=0-499closed500 bytes
Kafka consumer positionhalf-openposition is the next offset to read
"Jan 1 – Jan 31"closedboth days

The failure mode

Mixing the two inside one pipeline. A rollup job writes bucket keys as the bucket end timestamp; a dashboard queries WHERE bucket_ts >= :start AND bucket_ts < :end. The last bucket of every window is silently dropped, and the chart is short by one bucket at the right edge, which reads as a lagging data source, not an off-by-one.

It survives testing because a fixture whose timestamps never land exactly on a boundary passes. It shows up in production the moment a real counter emits at exactly :00 seconds, which is what a 1-second-resolution counter does.

Converting at the boundary

When the user says "Jan 1 to Jan 31", they mean both days. Internally that is >= 2024-01-01T00:00:00Z AND < 2024-02-01T00:00:00Z. The trap is the decrement: converting half-open to closed means subtracting one unit from the upper bound, and "one unit" is 1 for an integer ID, one second or one day for a timestamp depending on resolution, and undefined for a float. Do the conversion once, at the edge where the external format is closed, and keep the internal representation half-open.

When closed is the right call

User-facing ranges where the endpoint is a thing the user named rather than a boundary in a partition: calendar dates, page numbers, BETWEEN in SQL you generate for an analyst, HTTP byte ranges. Also when the domain is genuinely discrete and small: "chapters 1 through 12" has no meaningful [1, 13).

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How would you reason about the overlap test in a system you own?

Answer

The answer in the first minute: overlap is one comparison per side, a.start < b.end and b.start < a.end, and the only thing you have to decide before writing it is which interval convention the system uses. Get the convention wrong and the test is wrong at exactly one point: the boundary where two intervals touch.

Derive it rather than memorise it. Two intervals fail to overlap when one ends before the other begins, so overlap is the negation of that disjunction:

not (a.end <= b.start or b.end <= a.start)
=> a.end > b.start and b.end > a.start
=> a.start < b.end and b.start < a.end

The strictness falls out of the convention, not out of taste:

ConventionTest[0,10) vs [10,20)
half-open [s, e)a.s < b.e and b.s < a.eno overlap
closed [s, e]a.s <= b.e and b.s <= a.eoverlap at 10
Python
def overlaps(a, b):            # half-open [start, end)
    return a[0] < b[1] and b[0] < a[1]

Trace it the way the interpreter does:

  • overlaps((0, 10), (10, 20)) → 0 < 20 is True, 10 < 10 is False → False. Adjacent half-open intervals share no instant.
  • overlaps((0, 10), (9, 20)) → 0 < 20 True, 9 < 10 True → True.
  • overlaps((5, 5), (0, 10)) → 5 < 10 True, 0 < 5 True → True, which is wrong: [5, 5) is empty and overlaps nothing. The two-comparison form assumes non-empty intervals.

Failure modes, and how you catch them.

Four-branch enumeration. Writing containment, partial-left, partial-right and disjoint as separate branches gives four cases, and the boundary case is the one that gets dropped. It passes casual testing because random timestamps almost never land exactly on an endpoint. Detect it by testing the boundary explicitly: adjacent intervals, identical intervals, one nested inside the other, and a zero-length interval.

Empty intervals. As traced above, the standard test reports an empty half-open interval as overlapping. If your data can contain them: a zero-duration span from a clock that didn't advance, a booking with equal start and end: either guard with a[0] < a[1] and b[0] < b[1] or define them as non-overlapping by contract and assert it at the boundary where they're constructed.

Mixed conventions. The bug usually isn't in the comparison, it's that one subsystem stores closed dates (a hotel night of the 3rd to the 5th includes the 5th) and another stores half-open buckets (a metrics window [10:00, 10:05)). Encode the convention in the type or the field name and convert once at the edge.

Floating-point endpoints. With float timestamps, a.end == b.start may be a near-miss, so the strict comparison flips on rounding. Use integer ticks (nanoseconds, epoch millis) for interval endpoints.

When the pairwise test isn't the answer. It's O(1) per pair, but checking one interval against n stored intervals is O(n). Sort by start and sweep with a running maximum end for a batch overlap check, O(n log n), or use an interval tree when you need repeated stabbing queries. Reach for that only after measuring; the comparison itself is never the cost.

What to say about the system you own. State the convention, point at where it's enforced, and name the boundary test that proves it. If the decision turns on cost rather than semantics, that's the part you measure, not the comparison.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Walk through sorting by start time, including where engineers most often get it wrong.

Answer

The 60-second version. This is merge intervals. Sort by start time, then sweep once: each interval either extends the open range or starts a new one. The sort is O(n log n) and dominates; the sweep is O(n) time and O(n) output space. Sorting by end time is the classic wrong turn: it is the correct key for a different problem (maximum non-overlapping selection), and for merging it silently produces wrong output.

Python
def merge(intervals):
    if not intervals:
        return []
    intervals = sorted(intervals)          # 2-tuples/lists sort by start, then end
    out = [list(intervals[0])]
    for start, end in intervals[1:]:
        if start <= out[-1][1]:            # overlaps the open range
            out[-1][1] = max(out[-1][1], end)
        else:
            out.append([start, end])
    return out

Trace. Input [[1,3],[2,6],[8,10],[15,18]] is already start-sorted.

stepintervalstart <= out[-1][1]?out
init——[[1,3]]
1[2,6]2 <= 3 yes[[1,6]]
2[8,10]8 <= 6 no[[1,6],[8,10]]
3[15,18]15 <= 10 no[[1,6],[8,10],[15,18]]

Why start order is the guarantee. After sorting, every interval that could overlap the open range arrives before the range is closed. A later interval has start >= the current start, so it can only extend the range's end or fall outside it: it can never reach back and reopen a range already emitted. That is what makes one pass sufficient.

Where engineers get it wrong.

  1. Sorting by end time for merging. Counterexample: [[1,10],[2,3],[4,5]]. Sorted by end: [[2,3],[4,5],[1,10]]. Sweep: emit [2,3], 4 > 3 so emit [4,5], then 1 <= 5 extends to [1,10]. Result [[2,3],[1,10]]. Correct answer is [[1,10]]. The bug hides on inputs where the longest interval happens to start first.
  2. Applying the wrong sort to the wrong problem. For maximum non-overlapping selection, sort by end and greedily take the first interval that starts at or after the last chosen end: that greedy is provably optimal. Merging and selection need opposite keys; mixing them up is the single most common error here.
  3. Touching intervals. [1,2] and [2,3] merge under closed-interval semantics (start <= end) and stay separate under half-open (start < end). Pick one, state it, and keep the comparison consistent with it.
  4. Mutating the caller's list. intervals.sort() sorts in place; if the caller still needs the original order, use sorted().
  5. Assuming the input is already sorted. If intervals arrive from a log stream in start order, the sort is wasted and the whole thing is O(n), but verify that, don't assume it.

Follow-ups an interviewer will push on. Insert-interval and meeting-rooms reuse the same sweep with a different accumulator (a count or a heap of end times). If the input is huge or streaming, the O(n log n) sort is the bottleneck and you sort chunks or keep a heap instead.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Describe inserting into a sorted interval list and the evidence you would collect before relying on it.

Answer

Assume the list is sorted by start, intervals are half-open [start, end), and they are disjoint and non-touching: [1,3) and [3,5) would already have been merged. Insertion is one linear pass in three phases: copy intervals that end at or before the new start, absorb the overlapping run into one interval spanning the min start and max end, then copy the tail.

Python
# iv: list of [start, end), sorted, disjoint, non-touching
# new: [start, end)
def insert(iv, new):
    i, out = 0, []
    while i < len(iv) and iv[i][1] <= new[0]:   # before: end <= new.start
        out.append(iv[i]); i += 1
    while i < len(iv) and iv[i][0] < new[1]:    # overlap: start < new.end
        new = [min(new[0], iv[i][0]), max(new[1], iv[i][1])]; i += 1
    out.append(new)
    out.extend(iv[i:])
    return out

Trace iv = [[1,3],[5,8],[10,12]], new = [4,6]. Phase 1: iv[0][1]=3 <= 4, copy [1,3], i=1. Phase 2: iv[1][1]=8 <= 4? No; iv[1][0]=5 < 6? Yes, so new = [min(4,5), max(6,8)] = [4,8], i=2. iv[2][1]=12 <= 4? No; iv[2][0]=10 < 8? No, stop. Append [4,8], extend with [[10,12]] → [[1,3],[4,8],[10,12]].

The <= in phase 1 and < in phase 2 are what make touching intervals merge. Two concrete bugs follow from getting them wrong. First, using < in phase 1 (iv[i][1] < new[0]) leaves [1,3) and [3,5) as separate entries, so a point query for 3 matches two intervals and the list is no longer canonical. Detect it with an invariant check after every insert: for all j, out[j][1] <= out[j+1][0]. Second, appending new only inside the overlap loop drops the interval entirely when it overlaps nothing: inserting [20,25] past the end returns the list unchanged. Detect it with a length property: len(out) == len(iv) + 1 whenever new is disjoint from every interval.

Evidence to collect before relying on it, in order:

  1. Invariants as assertions: sorted by start, pairwise out[j][1] <= out[j+1][0], and union(out) == union(iv) ∪ new. Run these on every insert in tests.
  2. Differential test against a brute-force reference (append, sort, merge) over randomized inputs: 10^5 cases with random starts, ends and lengths, plus the boundary set: empty list, new before all, new after all, new spanning all, new exactly touching an endpoint.
  3. Cost at your real n. The three-phase pass is O(n) with one copy; re-sorting the whole list is O(n log n). At n = 10^6 that is roughly 20× the comparisons (log2 10^6 ≈ 20). Measure p99 insert latency at the n you actually run, not the class.

When the simpler re-merge wins: if n is small (a few thousand) or inserts are batched, sort once per batch and skip the three-phase pass. The constant factor of the extra pass is not worth the code. If inserts dominate and n is large, neither is right; keep an interval tree or balanced BST for O(log n) insert and pay it back at query time. The three-phase pass is the answer when the list is already sorted, inserts are interleaved with reads, and you want the read path to stay a plain binary search.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

How would you test a claim that the system depends on interval intersection of two lists?

Answer

Two claims hide in that sentence, and they need different tests. "The system depends on X" is causal: perturb X, the output moves. "X is interval intersection of two lists" is a correctness claim about a function. Test them separately: a passing correctness suite says nothing about dependency, and an ablation says nothing about whether the intersection is right.

Dependency: ablate, then instrument. Replace the intersection with a stub and watch the system's output. Three stubs are worth running: return [], return one fixed interval, and return the input unchanged. If the output is byte-identical under all three, the dependency is not real on the path you exercised: the code is dead, the result is cached, or something downstream ignores it. Then instrument: a call counter plus branch coverage (coverage.py --branch) tells you whether the production path reaches the function at all, and how often. A dependency that fires once per process is a different claim from one that fires per request.

Correctness: differential test against a brute-force oracle. The reference is O(n·m) and obviously right; the fast path is the two-pointer merge. Generate inputs with Hypothesis and compare.

Python
def intersect_ref(a, b):          # O(n*m), the oracle
    return sorted((max(x[0], y[0]), min(x[1], y[1]))
                  for x in a for y in b
                  if max(x[0], y[0]) < min(x[1], y[1]))

def intersect(a, b):              # O(n+m), the thing under test
    out, i, j = [], 0, 0
    while i < len(a) and j < len(b):
        lo, hi = max(a[i][0], b[j][0]), min(a[i][1], b[j][1])
        if lo < hi:
            out.append((lo, hi))
        if a[i][1] < b[j][1]:
            i += 1
        else:
            j += 1
    return out

Half-open intervals [start, end), so touching ranges do not intersect. Generator:

Python
from hypothesis import given, strategies as st

@st.composite
def interval_lists(draw, max_n=8, hi=100):
    pts = sorted(draw(st.lists(st.integers(0, hi), max_size=2*max_n, unique=True)))
    return [(pts[k], pts[k+1]) for k in range(0, len(pts) - 1, 2)]

@given(interval_lists(), interval_lists())
def test_matches_reference(a, b):
    assert intersect(a, b) == intersect_ref(a, b)

Sorted, disjoint and non-empty by construction, which is the function's precondition. Hypothesis shrinks any failure to a minimal case.

The bug this catches. Advancing both pointers after emitting an intersection looks fine on the happy path. Take a = [(0,10)], b = [(2,4),(6,8)]. The buggy version emits (2,4), advances both, and stops: it returns [(2,4)]. The oracle returns [(2,4),(6,8)]. Hypothesis finds this in well under a second; a hand-written test with one overlapping pair does not.

TestCatchesCost
Property/differential vs oraclewrong intersection, boundary off-by-one (< vs <=)seconds, needs a generator
Ablation (stub the function)false dependency claim, dead pathminutes, needs an injection seam
Mutation (lo <= hi, swap the pointer advance)tests that never touch the boundaryminutes
Instrumentation + branch coveragepath not exercised in prodcheap, needs a deploy
Timing at scalethe cost claimneeds real data

If the claim is about cost. n = m = 10^6: brute force is 10^12 pair comparisons, roughly 3 hours at 10^8 comparisons/s; the two-pointer is 2·10^6 steps, single-digit milliseconds. Back-of-envelope arithmetic, not a measurement: measure on your own data before quoting it.

What decides it. If the claim is "the system's output is determined by this intersection", ablation settles it; correctness testing is necessary but not sufficient. If the claim is "this is the bottleneck", only timing at production scale settles it. Name which claim you are testing before writing the test.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

How do you find the free time intervals (gaps) shared across multiple working schedules represented as disjoint sorted interval lists?

Answer

Finding common free time across multiple schedules means computing the gaps between intervals in the union of all schedules. Because each employee's schedule is already internally disjoint and sorted, we avoid an unconditional $O(N \log N)$ sort of all $N$ intervals by using a $k$-way merge with a min-heap of size $k$ (where $k$ is the number of schedules), running in $O(N \log k)$ time and $O(k)$ auxiliary space.

Mechanism

  1. Maintain a min-heap initialized with the first interval of each non-empty schedule: (start, end, schedule_idx, interval_idx).
  2. Maintain prev_end, tracking the rightmost end time observed across all processed intervals.
  3. Repeatedly pop the earliest interval (s, e). If prev_end < s, then (prev_end, s) is a mutual gap (unoccupied by any schedule). Append it to the result.
  4. Update prev_end = max(prev_end, e) to extend the current occupied span.
  5. Push the next interval from schedule schedule_idx into the heap, if one remains.
Python
import heapq

def employee_free_time(schedules: list[list[tuple[int, int]]]) -> list[tuple[int, int]]:
    # min-heap stores (start, end, schedule_idx, interval_idx)
    heap = []
    for i, sched in enumerate(schedules):
        if sched:
            heap.append((sched[0][0], sched[0][1], i, 0))
    heapq.heapify(heap)

    if not heap:
        return []

    free_time = []
    prev_end = heap[0][0]  # Initialize to the earliest start time seen

    while heap:
        s, e, s_idx, i_idx = heapq.heappop(heap)
        if s > prev_end:
            free_time.append((prev_end, s))
        if e > prev_end:
            prev_end = e
        if i_idx + 1 < len(schedules[s_idx]):
            nxt = schedules[s_idx][i_idx + 1]
            heapq.heappush(heap, (nxt[0], nxt[1], s_idx, i_idx + 1))

    return free_time

Complexity and Trade-offs

  • Time: $O(N \log k)$ where $N$ is total intervals across all schedules, and $k$ is the number of schedules. When $k \ll N$ (e.g., 5 teams with 10,000 meeting chunks), $N \log k$ beats an unconstrained $O(N \log N)$ flatten-and-sort.
  • Space: $O(k)$ working memory for the heap, versus $O(N)$ memory required if all intervals are collected and sorted upfront.

Failure Modes & Boundary Conditions

  • Touching vs. Disjoint intervals: Under half-open intervals [start, end), an interval ending at 12 and another starting at 12 ([9, 12) and [12, 14)) leave zero free time. The strict inequality s > prev_end ensures no spurious (12, 12) gap is emitted.
  • Leading and trailing boundaries: Without an explicit outer bounding interval (e.g., working day [09:00, 17:00)), the standard formulation excludes $(-\infty, \text{earliest_start})$ and $(\text{latest_end}, \infty)$. If global bounds are mandated, initialize prev_end = day_start and append (prev_end, day_end) if prev_end < day_end after draining the heap.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Given a set of meeting intervals, how do you compute the minimum number of rooms required to schedule all of them? Justify your approach and handle the case where one meeting starts exactly when another ends.

Answer

Clarify the convention first: I'll assume half-open intervals [s, e), so a meeting ending at 4 and one starting at 4 can share a room. Under that convention the minimum number of rooms equals the maximum number of meetings overlapping at any instant. Sort by start time, sweep with a min-heap keyed on end times, and keep the heap equal to the set of meetings still running when the current one starts.

python import heapq

def min_rooms(intervals): intervals.sort(key=lambda iv: iv[0]) heap = [] # end times of meetings still running peak = 0 for start, end in intervals: while heap and heap[0] <= start: heapq.heappop(heap) heapq.heappush(heap, end) peak = max(peak, len(heap)) return peak

The while drains every meeting that has already ended, so len(heap) after the push is exactly the number of meetings running at start. That invariant is what makes the running maximum the answer, and it is what you want when you debug a wrong count.

Trace on [(1,4), (2,5), (4,7), (6,9)]:

#intervalheap beforepoppedheap afterpeak
1(1,4)[]—[4]1
2(2,5)[4]—[4,5]2
3(4,7)[4,5]4[5,7]2
4(6,9)[5,7]5[7,9]2

Answer is 2. Step 3 is the boundary case: the meeting ending at 4 frees its room for the one starting at 4 because the test is heap[0] <= start. If the convention were closed [s, e], the test would be heap[0] < start and this input would need 3 rooms.

Complexity: sorting is O(n log n). Each interval is pushed once and popped at most once, so at most 2n heap operations at O(log n) each: O(n log n) total. The heap holds at most n end times, so O(n) space.

Alternatives: a sweep over 2n events (+1 at a start, −1 at an end, ends sorted before starts at equal timestamps) gives the same peak in O(n log n) time and O(n) space but no room assignment. Two sorted arrays of starts and ends with two pointers is also O(n log n) time and O(n) space, and simpler when you only need the count. The heap is the right pick when you also need to assign each meeting to a specific room: the popped end time is the room you reuse.

Failure modes worth naming: a max-heap of end times (you need the earliest end, not the latest); keying the heap on start times; forgetting to pop before pushing, which overcounts; reporting the final heap size instead of the running maximum. On [(1,10), (2,3), (11,12)] the final heap is [12], size 1, while the peak is 2; and using < instead of <= on half-open intervals, which counts touching meetings as overlapping and is off by one.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

How do you find the maximum number of concurrent overlapping intervals at any given point in time using a sweep-line algorithm?

Answer

What a strong candidate says first

Pin down the interval convention before writing anything: half-open [start, end) or closed [start, end]. It decides the tie-break, and the tie-break decides the answer. Then: turn each interval into two events, sort by timestamp, sweep a counter across them, track the running maximum. That is O(N log N) time and O(N) space for a static batch.

Tie-breaking is the whole problem

Under [start, end), an interval ending at T is already gone at T, so an interval starting at T does not overlap it. Process -1 before +1 at equal timestamps. Under closed [start, end], both are live at T, so process +1 first. Get this backwards and the peak is inflated by exactly the number of intervals that touch at a single point.

Code (checked against Python 3.11)

Python
def max_concurrent(intervals):
    events = []
    for s, e in intervals:
        events.append((s, 1))
        events.append((e, -1))
    events.sort()  # sorts by timestamp, then delta: -1 before +1 at equal ts
    cur = peak = 0
    for _, d in events:
        cur += d
        peak = max(peak, cur)
    return peak

events.sort() on tuples sorts by timestamp then delta, and -1 < 1, so the half-open tie-break comes for free. For closed intervals, sort with key=lambda ev: (ev[0], -ev[1]).

Trace: [1,5), [2,6), [3,4), [7,9)

Sorted events: (1,+1) (2,+1) (3,+1) (4,-1) (5,-1) (6,-1) (7,+1) (9,-1)

tdeltacurpeak
1+111
2+122
3+133
4-123
5-113
6-103
7+113
9-103

Peak is 3, held from t=3 to t=4 by [1,5), [2,6), [3,4). Note [1,5) and [2,6) overlap on [2,5), and [7,9) never overlaps anything.

Alternatives

Two-pointer over sorted starts and ends: sort starts, sort ends, advance whichever pointer is smaller, and on a tie advance the end pointer (half-open). Same O(N log N) time and O(N) space, without materialising 2N tuples.

Min-heap of end times: sort intervals by start, push each end, pop ends <= current start. O(N log N) time, O(N) space. Worth it when starts already arrive sorted, since then the only cost is the heap.

ApproachTimeSpaceUse when
Sweep-line eventsO(N log N)O(N)Static batch; simplest to reason about
Two-pointer sorted starts/endsO(N log N)O(N)Same, avoids 2N tuples
Min-heap of end timesO(N log N)O(N)Starts arrive sorted (streaming)
Difference arrayO(N + M)O(M)Timestamps in a small bounded range [0, M)

Failure modes

  • Inverted interval start > end: the sweep emits a -1 before its +1, cur goes negative, and the peak is understated. Validate start <= end on ingest.
  • Mixed conventions: treating closed intervals as half-open understates the peak by the number of touching pairs. Assert the convention at the pipeline boundary rather than trusting callers.
  • Empty input returns 0. Make sure callers read 0 as "no intervals", not "unknown".
  • The result is a point-in-time maximum, not a duration. If you need "how long were we above K", run a second sweep accumulating t_next - t_cur whenever cur > K.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Where does meeting rooms and peak concurrency matter, and where is it irrelevant?

Answer

Direct answer. Peak concurrency, the maximum number of intervals overlapping at any instant, is the minimum number of exclusive resources you need, and nothing else. It matters exactly where a resource is held for the whole interval and cannot be deferred: meeting rooms, database connections, worker threads, GPU slots, rate-limiter permits. It is irrelevant where work can wait in a queue, or where the resource is elastic or stateless, because there the binding constraint is total work or throughput, not simultaneity.

Mechanism. Sweep the 2n endpoints in time order, +1 at a start, −1 at an end, and track the running sum. The maximum of that sum is the answer. Sort ends before starts at equal timestamps so touching intervals do not count as overlapping.

Python
def peak(intervals):
    events = []
    for s, e in intervals:
        events.append((s, 1))
        events.append((e, -1))
    events.sort()          # at equal time, -1 sorts before +1
    cur = best = 0
    for _, d in events:
        cur += d
        best = max(best, cur)
    return best

# [(0,30), (5,10), (15,20)]
# events: (0,1)(5,1)(10,-1)(15,1)(20,-1)(30,-1)
# cur:      1    2    1      2     1      0   -> peak 2

Total duration is 40 minutes and the interval count is 3; neither appears in the answer. A min-heap of end times gives the same count and also the assignment, which room each meeting gets.

Where it matters vs where it does not.

SituationPeak concurrencyBinding constraint
Meeting rooms, seat bookingYes: minimum roomsexclusivity for the interval
DB connection poolYes: minimum connectionsone connection held per query
Worker / thread poolYesone thread held per task
Kafka consumersYes: capped at partition countone partition per consumer
Batch ETL, job queueNototal CPU-hours; jobs wait
Stateless request behind a cacheNothroughput (req/s); nothing held
Autoscaled web tierCost input onlyelastic; total work drives spend

Real defaults. HikariCP ships maximumPoolSize=10 and connectionTimeout=30000 ms; PostgreSQL defaults max_connections=100; AWS Lambda's default account concurrency is 1,000 per region. These are the ceilings a pool sized by peak overlap has to fit inside.

Failure mode. Sizing a pool by request rate or total request count instead of peak overlap. At 200 req/s with a 50 ms average hold time, average concurrency is 10, but a burst that overlaps 40 requests exhausts a 10-connection pool. Detection: HikariCP's hikaricp.connections.pending metric climbs and callers throw SQLTransientConnectionException: Connection is not available, request timed out after 30000ms. Cost: every waiting request burns a thread for up to 30 s, so p99 latency jumps from tens of milliseconds to the timeout and the pool becomes the outage.

When not to use it. If jobs can queue (batch, async workers), peak concurrency is a knob you set for throughput, not a derived minimum: cost is total work. If the resource is elastic (autoscaled pods, serverless), peak concurrency is a provisioning input, not a hard bound. If nothing is held across the interval (stateless reads), there is no overlap to measure.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

How do you select the maximum number of mutually compatible, non-overlapping intervals, and why does sorting by end time guarantee an optimal greedy choice?

Answer

The 90-second answer

Clarify the model before touching the algorithm: intervals are half-open [start, end), so one ending at 4 and one starting at 4 are compatible; the objective is maximum cardinality, not maximum total duration or weight; one resource, no preemption.

Then: sort by end time ascending, take the first interval, and sweep left to right, accepting any interval whose start is at least the end of the last accepted one. Sorting is O(n log n); the sweep is O(n).

The reason end time is the right key: the earliest-finishing interval leaves the most room to its right. Any optimal solution's first interval finishes no earlier than that one, so swapping it in keeps the rest of the solution feasible and never shrinks it. That is the whole argument, and it is what an interviewer wants to hear before the formal proof.

Worked trace

Input: (1,4) (3,5) (0,6) (5,7) (3,9) (5,9) (6,10) (8,11) (8,12) (2,14) (12,16)

Sorted by end time: (1,4) (3,5) (0,6) (5,7) (3,9) (5,9) (6,10) (8,11) (8,12) (2,14) (12,16)

Intervalstart >= current_end?Actioncurrent_end
(1,4)— (first)accept4
(3,5)3 >= 4? noskip4
(0,6)0 >= 4? noskip4
(5,7)5 >= 4? yesaccept7
(3,9)3 >= 7? noskip7
(5,9)5 >= 7? noskip7
(6,10)6 >= 7? noskip7
(8,11)8 >= 7? yesaccept11
(8,12)8 >= 11? noskip11
(2,14)2 >= 11? noskip11
(12,16)12 >= 11? yesaccept16

Result: (1,4) (5,7) (8,11) (12,16), four intervals. That is optimal here: the best you can pack into [0,12) is three, and (12,16) is the only interval reaching past 12, so four is the ceiling.

Why end time is optimal (exchange argument)

Let g_1..g_k be the greedy picks and o_1..o_m an optimal set, both ordered by start time. Show by induction that some optimal set agrees with greedy on its first r elements.

Base: g_1 has the minimum end time in the whole input, so end(g_1) <= end(o_1). Every o_i for i >= 2 starts at or after end(o_1), hence at or after end(g_1). Replacing o_1 with g_1 leaves a valid set of size m.

Step: assume an optimal set starts with g_1..g_{r-1}. Greedy picks g_r as the minimum-end interval compatible with g_{r-1}; o_r is also compatible with g_{r-1}, so end(g_r) <= end(o_r). Then start(o_{r+1}) >= end(o_r) >= end(g_r), so swapping o_r for g_r stays feasible.

Close: if m > k, the set g_1..g_k, o_{k+1}..o_m has o_{k+1} compatible with g_k, so the sweep would have accepted it. Contradiction, so k = m. Ties in end time are harmless; either interval works.

Implementation (checked against CPython 3.12)

Python
from typing import List, Tuple

def max_non_overlapping(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]]:
    if not intervals:
        return []
    ordered = sorted(intervals, key=lambda iv: iv[1])  # stable, keyed on end
    selected = [ordered[0]]
    current_end = ordered[0][1]
    for start, end in ordered[1:]:
        if start >= current_end:      # half-open [start, end): touching is fine
            selected.append((start, end))
            current_end = end
    return selected

Greedy keys that fail

KeyInputGreedy resultOptimal
Earliest start(0,10) (1,3) (4,6)(0,10): 1(1,3) (4,6): 2
Shortest duration(0,4) (3,6) (5,9)(3,6): 1(0,4) (5,9): 2
Latest finish(0,10) (1,2) (3,4)(0,10): 1(1,2) (3,4): 2

Complexity and edges

  • Time O(n log n), dominated by the sort; the scan is O(n). Space O(n) for the sorted copy, O(1) auxiliary if you sort in place.
  • The >= assumes half-open intervals. For closed [start, end], touching boundaries conflict, so the test becomes start > current_end.
  • Greedy is wrong the moment intervals carry weights: (0,10) weight 1, (1,2) weight 6, (3,4) weight 6. Greedy takes (0,10) for 1, the optimum is 12. Weighted interval scheduling needs a DP over intervals sorted by end time, with p(j) the last interval compatible with j.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

When and how do you apply coordinate compression to handle intervals spanning a large or sparse domain in segment trees and difference arrays?

Answer

Coordinate compression maps an unbounded or sparse set of real-world coordinates (e.g., timestamps in $[0, 10^9]$ or 64-bit offsets) to a compact dense rank space $[0, M-1]$, where $M \le 2N$ for $N$ intervals. You apply it when an algorithm's space or time complexity depends on the coordinate domain size $U$ rather than input count $N$, such as fixed-size difference arrays or static array-backed segment trees, and $U \gg N$.

Mechanism: Mapping and the In-Between Segment Pitfall

For point queries over point updates (e.g., counting overlapping intervals at exact points), collecting all unique endpoints, sorting, and deduplicating is sufficient. Query points map directly to their rank via binary search (bisect_left).

However, when intervals represent continuous ranges or segments: such as segment trees computing total covered length or range-addition difference arrays: compressing only the endpoints drops the space between adjacent points. If interval $[1, 10]$ and $[11, 20]$ are compressed merely by sorting unique endpoints ${1, 10, 11, 20} \to {0, 1, 2, 3}$, the distance between $10$ and $11$ collapses to $0$, falsely treating $[10, 11]$ as non-existent or merging adjacent disjoint boundaries.

To preserve elementary segments, each index $i$ in compressed space represents the segment $[coords[i], coords[i+1])$.

Python
from bisect import bisect_left

def compress_intervals(intervals):
    # intervals are half-open: [start, end)
    endpoints = set()
    for s, e in intervals:
        endpoints.add(s)
        endpoints.add(e)
    coords = sorted(endpoints)

    # Map continuous segment [coords[i], coords[i+1])
    # Segment tree or difference array operates over indices 0 .. len(coords) - 2
    compressed_intervals = []
    for s, e in intervals:
        idx_s = bisect_left(coords, s)
        idx_e = bisect_left(coords, e)
        compressed_intervals.append((idx_s, idx_e))

    return coords, compressed_intervals

Worked Trace: Difference Array with Continuous Length

Given intervals $[10, 50)$ and $[60, 100)$ in a domain $U = 10^9$:

  1. Endpoints: sorted unique coords = [10, 50, 60, 100] ($M = 4$).
  2. Intervals map to index ranges: $[10, 50) \to [0, 1)$ and $[60, 100) \to [2, 3)$.
  3. The compressed difference array has size $M - 1 = 3$, representing segments:
    • Segment 0: $[10, 50)$ of length 40.
    • Segment 1: $[50, 60)$ of length 10 (gap correctly isolated).
    • Segment 2: $[60, 100)$ of length 40.
  4. Increment $[0, 1)$: diff[0] += 1, diff[1] -= 1.
  5. Increment $[2, 3)$: diff[2] += 1, diff[3] -= 1.
  6. Prefix sum gives coverage counts: [1, 0, 1] for the three segments. Length covered is $1 \times 40 + 0 \times 10 + 1 \times 40 = 80$.

Trade-offs and Failure Modes

ApproachSpaceQuery / Update ComplexityConstraint
Coordinate Compression + Segment Tree$O(N)$$O(\log N)$Offline only: all coordinates must be known in advance.
Dynamic (Implicit) Segment Tree$O(Q \log U)$$O(\log U)$ nodes allocated on demandOnline queries allowed; avoids offline sorting pass.
Difference Array (Compressed)$O(N)$$O(1)$ update, $O(N)$ sweepOffline batch updates only, no interleaved queries.

Failure Modes:

  • Offline Requirement Violation: If coordinates arrive via a streaming API without an upper bound, coordinate compression fails because mapping ranks requires dynamic rebalancing (costing $O(N)$ re-indexing), requiring a dynamic segment tree or self-balancing interval tree instead.
  • Off-by-One Boundary Collapse: Using closed intervals $[s, e]$ without inserting $e+1$ into the coordinate set causes discrete difference arrays to improperly mark range ends.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

A teammate proposes a design that hinges on the sweep-line technique. How do you evaluate it?

Answer

Evaluate the design on three things, in this order: does the tie-breaking rule match the interval convention, does peak count actually answer the question being asked, and does the cost model fit the input size and shape. Everything else is detail.

1. Tie-breaking is the correctness hinge. The sweep is only correct if events at the same coordinate are ordered to match the interval convention. For half-open intervals [s, e), an end at x and a start at x do not overlap, so the end must be processed first. Python's tuple sort gives you that for free because -1 < +1:

Python
# intervals are half-open [s, e); checked against CPython 3.12
events = [(s, +1) for s, e in iv] + [(e, -1) for s, e in iv]
events.sort()          # (4, -1) sorts before (4, +1)
cur = peak = 0
for _, d in events:
    cur += d
    peak = max(peak, cur)

Trace it on iv = [(1, 4), (4, 7)]. Events sort to (1,+1), (4,-1), (4,+1), (7,-1). The counter runs 1, 0, 1, 0, so peak = 1: correct, the two intervals touch but do not overlap. Flip the tie so starts come first: (1,+1), (4,+1), (4,-1), (7,-1) gives 1, 2, 1, 0 and peak = 2. Off by one, and only on inputs that touch exactly at a boundary. If the convention is closed [s, e], the required order inverts. Ask which convention the design assumes and whether the code enforces it rather than inheriting it from a sort key.

2. Peak count may not be the answer. A sweep returns the maximum overlap. If the question is "how many rooms," that is enough. If it is "which interval goes in which room," the sweep does not produce an assignment: you need a min-heap of end times, popping a room when its end is at or before the next start. Confirm the design returns the quantity the caller needs, not a number that happens to be adjacent to it.

3. Cost and shape. The sweep is O(n log n) time and O(n) memory for 2n events. That is fine for a batch of a few million intervals. It is the wrong tool when coordinates are bounded and dense, a difference array over the coordinate range is O(n + C) and beats the sort, or when the input arrives as a stream, where the sort is the blocker and a heap over sorted-by-start input is the streaming answer.

ApproachTimeMemoryReturnsFails when
Sweep over 2n eventsO(n log n)O(n)peak countneed assignment; streaming input
Min-heap of end timesO(n log n)O(k) roomspeak + assignmentinput not sorted by start
Difference arrayO(n + C)O(C)peak countcoordinates sparse or large
Interval treeO(n log n) buildO(n)stabbing / overlap queriesone-shot batch peak

Failure modes to name. Boundary tie handled wrong (detect with a test of intervals touching at one point, not random data). Memory blowup at 2n events when n is large and intervals are long. Silent assumption that input is sorted when the heap variant is used. Overflow of the counter is not a real risk at realistic n.

If the design passes all three checks, it is sound. If it fails the tie-break, it is wrong on a class of inputs that casual testing will not surface.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How would you explain interval trees without using the usual slogan?

Answer

First 90 seconds

Skip the label and describe the machine. Keep the intervals in a balanced BST (AVL or red-black) keyed on start, and cache one extra number per node: max_end, the largest end anywhere in that node's subtree. The fields are start, end, max_end, left, right and nothing else. That cached maximum is the whole mechanism. At a node, with the overlap test s <= qe and e >= qs, ask whether anything in the left subtree can reach the query: if left.max_end < qs, no interval down there ends late enough, so the subtree is skipped without descending into it. The right subtree holds only larger starts, so it is worth entering only when node.start <= qe. Build is O(n log n), query is O(log n + k) for k reported intervals, insert and delete are O(log n) with rebalancing, space is O(n).

Trace: six intervals, one query

Stored: D[5,20], B[10,30], E[12,15], A[15,20], C[17,19], F[30,40]. Balanced on start: root E(12); E.left = D(5) with D.right = B(10); E.right = C(17) with C.left = A(15) and C.right = F(30).

max_end bottom-up: D = 20, B = 30, A = 20, F = 40, C = max(19, 20, 40) = 40, E = max(15, 30, 40) = 40.

Query [31, 35]:

  1. E(12,15): 12 <= 35 and 15 >= 31 both fail. Left test: D.max_end = 30 < 31, so D and B are pruned unseen. Right test: 12 <= 35, descend.
  2. C(17,19): no overlap. Left test: A.max_end = 20 < 31, prune A. Right test: 17 <= 35, descend.
  3. F(30,40): 30 <= 35 and 40 >= 31, report.

Three nodes visited, one interval returned. A flat scan visits all six and returns the same one. At n = 10^7 the tree visits log2(10^7) ~ 23 nodes plus one per reported interval, against 10^7 end comparisons for the scan.

Alternatives, and what decides

StructureQueryUpdateUse it when
Sorted array on startO(log n) to locate, then every earlier start must be scanned to test its end, O(n) worst caseO(n)Static set, intervals mostly disjoint, point/stabbing queries
Brute-force scanO(n)O(1)A few thousand intervals and one or two queries; building a tree costs more than the scan
Segment tree over compressed coordinatesO(log U + k)O(log U)Coordinates are dense bounded integers (86400 second-slots in a day is about 17 levels); counting coverage rather than listing it
Augmented BST interval treeO(log n + k)O(log n)Intervals arrive and expire: bookings, firewall rules, tracked memory regions
Centered (median-point) treeO(log n + k)O(n)Static set; two sorted lists per node, no rebalancing code
R-treeO(log n) descent, no worst-case guaranteeO(log n)Intervals in 2D, or on disk

Two things decide it. Does the set mutate between queries: that alone splits the sorted array from the augmented tree. And how big is k relative to n: once k approaches n every structure is O(n) and the search machinery buys nothing.

What breaks it

  • Stale max_end after a rotation, insert or delete. The prune then skips subtrees that do hold answers and the query under-reports with no error. Catch it with a differential test: replay one random insert/delete/query stream against a linear scan and compare result sets. A debug assert that max_end == max(end, left.max_end, right.max_end) catches the rest.
  • Pruning the right subtree on max_end. The right test is node.start <= qe; max_end says nothing about a subtree whose starts all sit past the query's end.
  • Closed [s, e] versus half-open [s, e) intervals. When one interval ends exactly where another begins the two conventions disagree. Write the predicate once and call the same function in the query, in the test oracle and in whatever merges the results.
  • Duplicate starts. Two intervals sharing a start collide on the key; key on (start, end) or keep a list per key, or the tree quietly loses one.

Sizing and other query shapes

Five 8-byte fields is 40 bytes per node, so 10^7 intervals is roughly 400 MB before allocator overhead: often the binding constraint in a process that also holds the data the intervals describe. The same pruning answers containment: for intervals containing [a, b], keep the left test but compare left.max_end against b, and descend right only when node.start <= a. Point stabbing is the overlap query with qs = qe.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

You have a static set of a million half-open intervals over timestamps up to 10^9, and you need to answer point-stabbing and range-overlap counts in logarithmic time. How do you use coordinate compression to build that index, and what breaks when many endpoints share the same coordinate?

Answer

Clarify first: half-open [l, r) or closed? Assume half-open, static set, offline build, online queries. The 10^9 domain stops mattering once you compress; N = 10^6 is what drives the build cost.

Collect all 2N endpoints, sort, dedupe → M ≤ 2N unique coordinates. The two queries are different shapes, so build two structures.

Point stabbing is a prefix sum over elementary segments. For each [l, r), diff[rank(l)] += 1 and diff[rank(r)] -= 1; prefix-summing gives cover[i] = number of intervals covering the segment [coords[i], coords[i+1]). Query at p: i = bisect_right(coords, p) - 1, return cover[i], or 0 when i < 0. O(log M) per query.

Range overlap, "how many intervals intersect [a, b)", is not a prefix-sum query. Count the complement instead: an interval misses [a, b) iff r <= a or l >= b, and for non-empty intervals those two sets are disjoint (l < r makes both impossible). So count = N - bisect_right(sorted_ends, a) - (N - bisect_left(sorted_starts, b)). Two binary searches over the raw, duplicate-bearing endpoint lists.

Python
from bisect import bisect_left, bisect_right

class IntervalIndex:
    def __init__(self, intervals):
        intervals = [(l, r) for l, r in intervals if l < r]  # drop empties
        coords = sorted({x for l, r in intervals for x in (l, r)})
        self.coords = coords
        diff = [0] * (len(coords) + 1)
        for l, r in intervals:
            diff[bisect_left(coords, l)] += 1
            diff[bisect_left(coords, r)] -= 1
        self.cover = []
        run = 0
        for i in range(len(coords)):
            run += diff[i]
            self.cover.append(run)
        self.starts = sorted(l for l, r in intervals)
        self.ends = sorted(r for l, r in intervals)
        self.n = len(intervals)

    def point_stab(self, p):
        i = bisect_right(self.coords, p) - 1
        return self.cover[i] if i >= 0 else 0

    def range_overlap(self, a, b):
        left = bisect_right(self.ends, a)            # r <= a
        right = self.n - bisect_left(self.starts, b) # l >= b
        return self.n - left - right

Trace with A=[0,5), B=[5,10), C=[2,7). coords = [0,2,5,7,10]. diff = [1,1,0,-1,-1,0]. cover = [1,2,2,1,0]. point_stab(3): bisect_right(coords,3)=2, i=1, cover[1]=2 (A, C). point_stab(6): i=2, cover[2]=2 (B, C). range_overlap(8,9): left = bisect_right([5,7,10],8)=2, right = 3 - bisect_left([0,2,5],9)=0, result = 3-2-0=1 (only B).

What shared coordinates break.

Counting from the deduped array. Compression collapses duplicates, so a binary search over unique coordinates counts distinct coordinates, not intervals. Intervals [0,5), [0,5), [5,10) with query [5,6): unique ends are [5,10], bisect_right(unique_ends, 5) = 1, but two intervals end at 5, so the true left count is 2. You get 3-1-0=2 instead of 1. Keep multiplicity: sort raw endpoints with duplicates (as above), or keep a frequency array over compressed coordinates and prefix-sum it. The difference array is safe because it adds +1 per interval; the trap is reusing the deduped list for counting.

Treating compressed indices as points. If p sits between coords[i] and coords[i+1], bisect_left returns i+1, the wrong segment; use bisect_right - 1. A segment tree over compressed coordinates has the same off-by-one: [l, r) updates [rank(l), rank(r)-1], not [rank(l), rank(r)]. The inclusive update overcounts at rank(r), which is exactly the bug that surfaces when many intervals share an endpoint.

Empty intervals in the complement formula. [l, l) intersects nothing, but the complement test counts it as intersecting whenever a < l < b, since r = l fails both r <= a and l >= b. Drop l == r at build time, they cancel in the difference array anyway, and use the filtered count as N.

Also name: query point outside the coordinate range (return 0), inverted l > r (garbage in, garbage out), and closed [l, r] (then diff[rank(r)+1] -= 1 and the segment interpretation shifts).

Complexity: O(N log N) build, O(N) space, O(log N) per query.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

What failure would you inject to check a team's understanding of segment trees?

Answer

Core answer (first 90 seconds)

Inject a lazy-propagation ordering failure: apply a range update, then query a strict subrange of it. It is the cheapest test that separates a team that has internalized the push-down invariant from one that has memorized the template.

Concretely, hand them an array of 8 elements, [1,2,3,4,5,6,7,8], a segment tree supporting range-add and range-sum, and two operations in this order:

  1. add(2, 5, +10): add 10 to indices 2 through 5.
  2. query(3, 3): sum of index 3 alone.

The correct answer is 14. A tree that applies the +10 tag to the canonical nodes covering [2,5] (the node for [2,3] and the node for [4,5]) but descends to leaf 3 during the query without pushing that tag down returns 4. Same code, same input, one missing push.

Why this failure and not another

Range updates are where segment trees stop being a memorized template. A point-update tree is a recursive loop anyone can reproduce; lazy propagation is an invariant: a node's stored aggregate is correct for its range, and any pending tag applies to its children, not itself. The subrange query is what forces the invariant to be exercised, because the query path crosses a node that holds a pending tag. A full-range query after the update would pass even in the buggy tree, since the root's aggregate already includes the tag.

A second injection, for the update path

Update a[0] from 1 to 100, then query(0, 7). Correct: 135. A tree that rewrites the leaf but never pulls the new value up the path returns 36: the pre-update total. This catches the mirror-image bug: push-down without pull-up.

What each injection catches

Injected sequenceBug it exposesWrong output
add(2,5,+10) then query(3,3)no push-down on the query path4 instead of 14
a[0]=100 then query(0,7)no pull-up on the update path36 instead of 135
add(2,5,+10) then add(4,6,+1) then query(5,5)tag overwrite instead of tag composition7 instead of 17

The third is the sharpest. Index 5 sits in both updated ranges, so its correct value is 6 + 10 + 1 = 17. A tree that assigns the new tag to node [4,5] rather than adding to it returns 7. Teams that pass the first two often fail this one, because composing tags is the part they never had to reason about.

How to check understanding, not just output

Have them predict the output before running, then name the node that holds the pending tag at the moment of the query. A team that gets 14 but cannot say "the tag is on [2,3] and gets pushed to leaf 3" pattern-matched the fix. Ask them to state the invariant in one sentence; the correct one is that a node's aggregate is always correct for its range and tags are owed to children.

Failure modes of the test itself

A team that has never written lazy propagation fails for the wrong reason: calibrate to what they claim. And a team can pass by copying a known-correct implementation; the prediction step is what closes that gap. Keep the array small enough to trace by hand: 8 elements, three operations, no tooling required.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How should on-call treat an alert that names lazy propagation as the cause?

Answer

The named cause is a hypothesis, not a diagnosis. Alerts fire on a condition someone wrote; the string "lazy propagation" in the alert body is that author's guess about why. On-call establishes impact first, then falsifies or confirms the guess. Reading the segment tree code is the last step, not the first.

First five minutes

  1. What does the alert actually measure? If it fires on a symptom (p99 latency, error rate, a wrong-value report) the cause string is a comment. If it fires on a cause-named condition, such as a counter lazy_push_misses, the alert is low-signal and should be rewritten to fire on the symptom it was meant to proxy.
  2. Is there user impact? A wrong-value alert is a correctness incident: page. A latency alert is a degradation: page if the path is critical, otherwise queue it.
  3. Only then look at the mechanism.
Alert fires onWhat it provesOn-call action
p99 range-update latency > 250 ms for 5 mSymptom; cause unprovenCheck QPS and tree size, roll back the last deploy, page if user-visible
Wrong query results or checksum mismatchCorrectnessPage immediately; the lazy tag is a prime suspect
Counter named lazy_propagation_errorsNothing on its ownTreat as a lead; find the symptom it was meant to proxy

Falsify the hypothesis cheaply

Two failure modes account for most incidents blamed on lazy propagation, and they look nothing alike.

Wrong values: the tag is applied to children but never cleared on the parent. Trace a tree over [1,4], all zeros, with add 5 to the whole range, then two queries:

  • apply(root, 5, 1, 4) → tree[1] = 20, lazy[1] = 5.
  • Query [1,2] pushes: tree[2] = 10, lazy[2] = 5; tree[3] = 10, lazy[3] = 5. With the bug, lazy[1] stays 5.
  • Query [3,4] pushes again: tree[2] = 20, lazy[2] = 10; tree[3] = 20, lazy[3] = 10.
  • Query [1,1] pushes a third time and applies lazy[2] = 15 to the leaf: it returns 15. The correct answer is 5.

No latency dashboard shows this. Detection is a property test that runs interleaved range updates and queries against a naive array.

Latency: someone "fixed" a lazy bug by pushing to every covered leaf, so a range update is O(n) instead of O(log n). In a hypothetical service with n = 10⁶, a 10³-element range update touches ~10³ nodes instead of ~20: a 50× jump. That is the shape of a p99 that goes from 6 ms to 250 ms while p50 barely moves.

Mitigate

Roll back the deploy that touched the tree if the alert started inside one deploy window. For a correctness alert, fail closed: stop serving the affected queries rather than returning wrong aggregates. Do not rewrite lazy propagation live at 3 a.m.; the fix is a code change with a test.

Trade-offs

Cause-based alerts are cheap to write and rot fast; symptom-based alerts survive refactors. Eager updates are simpler and correct by construction: use them when ranges are small or n is bounded, and keep lazy propagation for large n with many range updates. An alert that names a mechanism is a sign the rule was written by whoever last debugged it, not by whoever owns the symptom.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

What belongs in a runbook section on binary indexed trees, and what does not?

Answer

A runbook section is an operational document: it holds what an on-call engineer needs to diagnose and fix the structure at 3am, and nothing that only helps someone learning it. For a Fenwick tree that splits cleanly.

Belongs: the invariant, stated as a checkable fact. bit[i] holds the aggregate of a[i - lowbit(i) + 1 .. i], where lowbit(i) = i & -i. The array is 1-indexed and bit[0] is unused. When a prefix sum comes back wrong, this line is what you compare against.

Belongs: the two loops, verbatim, with the language and version they were checked against. Python 3.12:

Python
def update(i, delta):          # 1 <= i <= n
    while i <= n:
        bit[i] += delta
        i += i & -i

def prefix(i):                 # 0 <= i <= n
    s = 0
    while i > 0:
        s += bit[i]
        i -= i & -i
    return s

Belongs: the cost bound with numbers. Each call walks at most log2(n) + 1 indices. For n = 10^6 that is 20 iterations per operation; the array is n + 1 int64s, 8 MB. A range sum is prefix(r) - prefix(l - 1), two walks.

Belongs: the failure mode and how to detect it. The aggregate must be invertible. update propagates a delta by addition, so a point update that lowers a value cannot be undone for max or min. The structure does not raise; it returns a stale maximum. Detect it at startup with an assertion against a brute-force recompute on a random sample:

Python
assert prefix(n) == sum(a[1:])

Remediation is a rebuild: recompute bit from a in O(n) by setting bit[i] = a[i], then for each i, j = i + (i & -i); if j <= n: bit[j] += bit[i].

Belongs: the trace you paste when the assertion fires. With n = 8, update(3, 5) touches indices 3 → 4 → 8; prefix(7) reads 7 → 6 → 4. If the touched set in the logs differs, the index base is wrong.

Does not belong: the derivation. Why i & -i isolates the lowest set bit is a two-line proof, not a runbook step. Nobody reads it during an incident.

Does not belong: the segment-tree comparison. "Use a segment tree when the aggregate has no inverse" is a design decision made before deploy, recorded in the design doc. In the runbook it is noise.

Does not belong: benchmark numbers from a developer laptop. Latency depends on cache behaviour and the caller's access pattern; a runbook figure that was never measured on the production host is worse than none.

Does not belong: the correctness proof, the complexity derivation, or a worked example of building the tree from scratch. Those live in the design doc and the code comments.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

How would you review a pull request whose risk is the boundary condition in tie-breaking?

Answer

I read the comparison first, then decide whether its tie-break is total enough for how the result is consumed. The boundary case is the whole risk, so the review is about the diff and the tests, not about the algorithm in the abstract.

1. Find the comparison and ask what it returns for two elements equal on the primary key. If it returns 0, the tie-break is whatever the sort or container does next, and that is where the bug lives.

2. Check the container. Java's TreeSet/TreeMap use compareTo == 0 as equality, not equals. A comparator that returns 0 for two distinct elements silently drops one:

Java
// Java 17
record Event(long ts, long id) {}

var byTs = Comparator.comparingLong(Event::ts);
var set = new TreeSet<>(byTs);
set.add(new Event(1000, 7));
set.add(new Event(1000, 3));
System.out.println(set.size()); // 1

Trace: byTs.compare(e7, e3) calls Long.compare(1000, 1000) → 0. TreeSet.add reads 0 as "already present" and discards the second element. Size is 1, and the survivor is the first inserted. Change the comparator to Comparator.comparingLong(Event::ts).thenComparingLong(Event::id) and the same two adds give size 2, ordered (1000,3) then (1000,7).

3. Check the tests. A suite that only uses distinct timestamps proves nothing about the boundary. I ask for a test with two elements equal on the primary key that asserts the full order, not just the set of elements.

CheckWhat I look forWhy it decides the review
Comparator totalityReturns 0 only for genuinely equal elementsTreeSet/TreeMap treat 0 as a duplicate
Tie-break keyA unique secondary key (id, sequence)Without it, order is input-dependent
Sort stabilityList.sort/Collections.sort are stable; Arrays.sort on primitives is notEqual elements keep input order only where stability is guaranteed
Downstream useCursor pagination, dedup, top-kDetermines whether the order must be total

Failure modes to name in the review. Cursor pagination ordered by created_at alone: with ties, WHERE created_at > last skips rows sharing the boundary timestamp and >= duplicates them across pages; the fix is ORDER BY created_at, id with both columns in the cursor. A comparator fed from HashMap iteration or a parallel stream: equal elements come out in a different order each run, so a test that passes locally fails in CI. A comparator that violates transitivity throws IllegalArgumentException: Comparison method violates its general contract! from TimSort: that is a crash, not a wrong order, and it means the comparator is broken, not the data.

Merge criteria. If the sorted order only drives display, a stable sort is enough and I approve with a comment. If it feeds a cursor, a dedup, or a TreeSet, the tie-break must be unique and deterministic, and I block until the secondary key is in the comparator and a boundary test exists. When the author argues the tie "can't happen," I ask for the constraint or index that enforces it; if there isn't one, the tie can happen.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How would you brief product on why floating-point endpoints delays a ship date?

Answer

The 90 seconds

"Interval endpoints are stored as float64. Float64 can't represent 0.1 or 0.2 exactly, so an endpoint computed as start + ttl lands a few ULPs off the value the spec names. A half-open window [start, expiry) then admits a request that should be rejected: a wrong answer, not a slow one. The fix is to store endpoints as integer ticks (microseconds) and compare integers. That touches the wire format, the DB column and the client SDK, so it's 4–5 days plus a migration. The alternative is a 1-day epsilon patch that hides the symptom for normal-sized intervals and leaves it for tiny ones. I need you to pick: ship on time with a known wrong-answer class, or slip the date."

Assumption to state out loud: endpoints arrive from config or arithmetic. If they're parsed from decimal text, the fix is cheaper: parse to integer ticks at the edge and nothing downstream changes.

Why "floating point is fuzzy" won't land

Product has heard that line and it means nothing. Give them the trace:

Python
>>> start, ttl = 0.1, 0.2          # seconds, from config
>>> expiry = start + ttl
>>> expiry
0.30000000000000004
>>> expiry == 0.3
False
>>> 0.3 < expiry                   # request at the boundary is let through
True

The spec says the window is [start, expiry). The code says t < expiry. At t = 0.3 the request is inside when it should be outside. One extra request per boundary hit: for a rate limiter, one extra call; for a billing window, one extra second on the invoice.

Scope, in their units

  • Endpoints: count them. "Seven interval comparisons across three services", not "several places".
  • Exposure: instrument it. If it's 1 request in 10^4 (hypothetical, and say how you measured), say that number.
  • Cost of each fix:
OptionWorkShip dateResidual risk
Epsilon compare (abs(a-b) < 1e-9)1 dayon timewrong for intervals under 1e-9; two endpoints can both "equal" a third
Integer ticks at the boundary only3 days+3mixed representations at the seam
Integer ticks end-to-end + backfill5 days+5wire, DB and SDK change

What product decides

Which row. Engineering can rank correctness; only product can price a slipped date against a wrong-answer class. Don't ask "should we fix it": ask "which of these three".

What not to say

  • "Floating point is imprecise." True, useless, and it invites "so is everything".
  • "It's an edge case." Every boundary is an edge case; that's what a boundary is.
  • A date you haven't scoped. Give the range and the assumption behind it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

What trade-off does intervals over time zones and calendars force that a junior answer usually skips?

Answer

The trade-off an interval forces: pin it to an instant or to a local calendar label, and whichever one you pin, the other one varies.

Assume the usual setup for a product with users in more than one IANA zone and at least one recurring event ("standup at 09:00", "the invoice period starts on the 1st"). Then:

  • Pin the instant: the interval's length is exact, and the local clock time it lands on drifts when the zone changes offset.
  • Pin the local label: 09:00 stays 09:00, and the elapsed length stops being constant - consecutive local days are 23, 24 or 25 hours.

You cannot have both. The UTC-to-local mapping moves by an hour twice a year in DST zones, and a civil month is 28-31 days. "Just store UTC" is the answer that skips the trade-off: it silently picks instant anchoring and breaks every wall-clock-anchored recurrence.

Mechanism. Europe/London jumps 01:00 to 02:00 on 2026-03-29 and falls back 02:00 to 01:00 on 2026-10-25, so local 01:00-01:59 does not exist on the first date and happens twice on the second. Python 3.9+ zoneinfo resolves both through the fold attribute from PEP 495: fold=0 selects the offset before the transition, fold=1 the one after, and an unset fold silently gives you one of the two. Adding a timedelta to an aware datetime adds to the wall-clock fields, then re-evaluates the offset for the new local time.

Python
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

lon = ZoneInfo("Europe/London")
t0 = datetime(2026, 3, 27, 9, 0, tzinfo=lon)   # Friday 09:00, offset +00:00

print(t0 + timedelta(days=2))                                        # label anchoring
print((t0.astimezone(timezone.utc) + timedelta(days=2)).astimezone(lon))  # instant anchoring

Output:

2026-03-29 09:00:00+01:00
2026-03-29 10:00:00+01:00

Same input, same two-day delta. The first result is 47 real hours after t0 and keeps the 09:00 wall clock; the second is exactly 48 hours and has moved the wall clock to 10:00. That is the trade-off in two lines.

Anchored toTypical intervalLocal labelElapsed lengthOrdering
Instant (UTC)session TTL, "respond within 4h" SLA, rate-limit windowdrifts 1h across a transitionexacttotal, comparable across zones
Local calendardaily 09:00 standup, "1st of the month" periodexact23-25h per day, 28-31 days per monthper zone, and ambiguous in the repeated hour unless the offset is stored

Failure modes. A job keyed on UTC midnight is not "daily" for anyone: it is 01:00 in London during BST and 19:00 the previous day at UTC-05:00, so a local-day streak counter double-counts or skips on transition days. Catch it by replaying the scheduler over both transition dates for every zone in the product's zone list and asserting exactly one occurrence per local calendar day. Overlap checks with assumed durations break too: two 30-minute meetings at local 01:15 and 01:45 on 2026-10-25 are 90 minutes apart in real time if they land in different folds, and 01:15 on 2026-03-29 is not an instant at all - compute overlap on instants and assert end > start after resolution. Calendar arithmetic is not duration arithmetic: 2026-01-31 plus one month is 2026-02-28. And tzdata moves the goalposts: zones get redefined, so re-deriving a past instant from a stored rule can return a different instant than the one you wrote; pin the tzdata version and store the resolved instant beside the rule that produced it.

Choosing. Instant anchoring for anything measuring elapsed time or needing global order - TTLs, SLA clocks, rate limits, audit logs. Local calendar anchoring for anything a human or a contract named in civil time - standups, exchange hours, monthly billing cutoffs, "midnight local" deadlines. A mixed interval such as "every day at 09:00 local for 30 minutes" needs both: the recurrence rule is calendar, the duration is instant.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How does rate limiting as an interval problem interact with rollback, and where do people ignore that?

Answer

The 90-second answer. Rate limiting is a decision over a time interval, "how many requests in the last 60 seconds", and that interval is state the limiter owns. Rollback rewinds your state: a config, a deploy, a transaction. It does not rewind the limiter's interval. So after a rollback the limiter is still holding counts from the regime you rolled back from, and that is where the two collide. Three places, and people miss all three:

RollbackWhat the interval doesSymptom
Config: 100/s → 10/sWindow still holds the old regime's admits~55s of total rejection after tightening
Deploy: limiter's state layout changesNew code reads keys the old code never wroteLimit reads 0, one full window of burst admitted
Transaction: work fails and rolls backThe attempt was already countedRefunding the token lets a failing client retry unbounded

Config rollback, with numbers. Take a 60-second sliding window with a cap of 6000 (100 req/s sustained), built from 60 one-second buckets. At steady state each bucket holds 100, so the window sums to 6000. Roll back to 10 req/s, cap 600, at t=0. The sum is 6000, still ≥ 600, so every request is rejected. Buckets expire one per second, each dropping 100, and no new admits are added, so the sum falls 100/s and crosses 600 at t=54s; the first request gets through at ~55s. A rollback meant to protect the system takes it fully offline for ~55 seconds. The rollback is instant; its effect is not, because the window is memory, and the drain rate is set by the old admit rate, not the new limit.

Deploy rollback. If the old limiter used a fixed 60s counter and the new one uses 60×1s buckets, rolling back points the old code at keys the new code never wrote. The counter reads zero and the limit is off for one window. Keep the state layout stable across the rollback, or drain before switching.

Transaction rollback. The limiter counts attempts, not successes. Refunding a token when the work rolls back means a client whose downstream always fails gets unlimited attempts against the failing dependency: exactly when the limiter matters.

Python
def handle(req):
    if not limiter.allow(req.key):   # consumes one token
        return 429
    try:
        return do_work(req)          # may raise and roll back
    except Exception:
        # limiter.refund(req.key)    # don't: bounds attempts, not successes
        raise

Detection. Track admitted vs. succeeded per key; a widening gap means budget is being spent on failures. For distributed limiters that hand out leases, compare outstanding leases to the configured limit: leaked leases are capacity that never returns.

The trade-off that decides it. An exact log of timestamps lets you re-evaluate the last 60s under a new limit after a config rollback, so the rollback behaves correctly. A bucketed counter can't: it only holds sums. Exactness costs unbounded memory under rejected load, which is when the limiter is under the most pressure. Bucketed counters bound memory and cap the error at one bucket's count (here 100 requests, ~1.7% of the window); take that if you can tolerate the rollback window being approximate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

What is the smallest experiment that would change your mind about very large interval sets?

Answer

The smallest experiment is a one-machine run on a 1% sample that measures a single number: the merge ratio. How many intervals survive after sorting and coalescing overlaps. Everything else about very large interval sets follows from that number.

Assume 10^9 intervals, each two int64 endpoints, so 16 GB raw. That does not fit an 8 GB container, so the real question is whether the merged form does. The candidate design is a sorted array of disjoint intervals plus binary search for stabbing queries: fastest and simplest if it fits.

The experiment: take 10^7 intervals (1% of the real set), sort, coalesce, and print the surviving count and peak RSS.

Python
import resource

def merge(intervals):
    intervals.sort()
    out = []
    for lo, hi in intervals:
        if out and lo <= out[-1][1]:
            if hi > out[-1][1]:
                out[-1][1] = hi
        else:
            out.append([lo, hi])
    return out

N = 1_000_000
sample = [(100 * i, 100 * i + 1000) for i in range(N)]   # length 1000, spacing 100
merged = merge(sample)
print(len(merged), merged[0], merged[-1])
print("peak RSS MB", resource.getrusage(resource.RUSAGE_SELF).ru_maxrss // 1024)

Trace: the list is already sorted. The first interval seeds out = [[0, 1000]]. Each next interval starts 100 before the current merged end, so it extends that end by 100; after interval i the end is 100*i + 1000. The last interval is (99_999_900, 100_000_900), so the merged set collapses to one interval. Output:

1 [0, 100000900] [0, 100000900]

Change the spacing to 2000 and the same 10^6 intervals never overlap: merged count is 1,000,000. Same N, same code, ratio 1 versus 10^6. That is the mind-changing part.

Arithmetic: raw 10^9 × 16 B = 16 GB. A merge ratio of 100 gives 10^7 merged intervals × 16 B = 160 MB, which fits. A ratio of 1 gives 16 GB, which does not. The sample's ratio × 100 is the projection.

Decision rule: if projected peak RSS is under 50% of container memory, keep the in-memory sorted array. Otherwise go external sort plus streaming sweep, or a compressed bitmap.

Failure modes. Uniform random sampling destroys the clustering real interval sets have: IP ranges sit in a few /8s, time ranges sit in business hours. Detect it by computing the ratio on a random sample and on a contiguous time-ordered sample; if they differ by more than 2×, the sample is lying and you need stratified sampling. Measuring len(merged) without peak RSS misses the sort's transient allocation, which for 10^7 tuples is the larger number. And linear extrapolation of the ratio breaks once density crosses 1: below it almost nothing merges, above it almost everything does, and the transition is sharp.

Alternatives. If intervals come from a fixed-length window generator, density = N·L̄/W predicts the ratio with no run: cheaper, wrong whenever there are clusters. A full-scale run is definitive but costs a big box and hours; only worth it once the sample says you are near the boundary. Skipping the measurement entirely, start with an external sort or a compressed bitmap and pay constant overhead, is right when the workload is write-heavy or the data is genuinely unbounded.

Do not run it when the set is small enough that the answer is obvious, or when being wrong is cheap, as in a batch job you can simply re-run.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

What would you ask a candidate who recites testing interval code but cannot apply it?

Answer

Don't ask them to list boundary cases: that is the recitation. Ask them to produce a failing input for a merge that is wrong, then to state the interval convention before answering a case.

Probe 1: hand them a bug and ask for the input that breaks it.

Python
def merge(intervals):          # closed intervals [start, end]
    intervals.sort()
    out = []
    for s, e in intervals:
        if out and s <= out[-1][1]:
            out[-1] = (out[-1][0], e)
        else:
            out.append((s, e))
    return out

Trace merge([(0, 10), (2, 3)]):

  • sort → [(0, 10), (2, 3)]
  • (0, 10): out is empty → out = [(0, 10)]
  • (2, 3): 2 <= 10 → out[-1] = (0, 3) → out = [(0, 3)]
  • returns [(0, 3)]; correct is [(0, 10)]

The bug is nesting: the merge overwrites the end without comparing it to the old one. Touching ([(0,10),(10,20)] → [(0,20)]) and identical pairs pass; a zero-length interval inside another fails for the same nesting reason. A candidate who recites the four shapes but cannot apply them names a touching case and is wrong.

Probe 2: make them fix the convention before the case.

"Intervals are half-open [start, end). Do [1, 3) and [3, 5) overlap? What does merge return for [[1,3), [3,5)]?"

ProbeRecited answerApplied answer
Failing input for the merge above"add a touching case"[(0,10),(2,3)] → [(0,3)], expected [(0,10)]
[1,3) vs [3,5)"touching, so they overlap"disjoint; merge keeps both

The predicate is a[0] < b[1] and b[0] < a[1] for half-open, <= for closed. 1 < 5 holds, 3 < 3 does not, so no overlap. "Touching intervals overlap" is a fact about closed intervals that the reciter never bound to a convention.

Follow up with "why does that input fail?" A candidate who guessed the input by trying pairs will not be able to say that the end is overwritten rather than maxed. Then ask for the one-line fix: out[-1] = (out[-1][0], max(out[-1][1], e)).

Which probe to use. With ten minutes, probe 1 is the highest-yield: it cannot be answered from memory, and the trace is checkable. Probe 2 is faster and tests whether they know the boundary is a convention rather than a fact: use it when you have already watched them write the predicate. A PR-review exercise tests more but is noisy: candidates spend the time on style. Pick by what you still don't know: can they read code (probe 1), or do they know the spec (probe 2).

Where the probe itself fails. If the candidate has seen this exact merge, the bug is free; keep a second one in reserve, such as a merge that assumes sorted input. And a candidate can brute-force the failing input by trying every pair without understanding it: the "why" follow-up is what separates them, so do not skip it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How would you document choosing the technique so the next owner can operate it?

Answer

The next owner needs three things written down: the assumption the choice rests on, the invariant the structure maintains, and the measurement that would prove the assumption wrong. Put it in an ADR next to the code (Nygard's format (Context, Decision, Consequences)) not in a wiki that rots.

Context: the load-bearing number. State the update:query ratio you measured, not "mostly reads". For example: "10^6 intervals, ~200 updates/day, ~5×10^4 range queries/day, ratio 1:250." That one number is what makes the decision reproducible by someone who wasn't in the room.

Decision: the structure and why.

WorkloadStructurePer-op costNamed implementation
Static set, many queriessort once, prefix-max of ends, binary searchO(n log n) build, O(log n) queryPython sorted + bisect; Guava ImmutableRangeSet
Frequent insert/deleteinterval tree (BST on low endpoint, max-end augmentation)O(log n) update, O(log n + k) queryJava TreeMap; Guava TreeRangeSet; C++ boost::icl::interval_map
Range update + range querysegment tree, lazy propagationO(log n) bothhand-rolled; no stdlib
Point update, prefix sumFenwick treeO(log n) bothhand-rolled

Why the static case is cheap: one sort orders every low endpoint, and a prefix-max of high endpoints answers a stabbing query in one binary search. No rebalancing, no per-node bookkeeping. A dynamic structure pays log n per operation to keep the tree balanced as keys move; that is the price of not knowing the order in advance.

Python
import bisect

def build(intervals):
    ordered = sorted(intervals, key=lambda iv: iv[0])   # by low endpoint
    starts = [iv[0] for iv in ordered]
    prefix_max_end, m = [], float('-inf')
    for iv in ordered:
        m = max(m, iv[1])
        prefix_max_end.append(m)
    return starts, prefix_max_end

def contains(starts, prefix_max_end, t):                 # O(log n)
    i = bisect.bisect_right(starts, t)
    return i > 0 and prefix_max_end[i - 1] >= t

Trace on [(0,100),(10,20)]: starts=[0,10], prefix_max_end=[100,100]. Query 50 → bisect_right=2, prefix_max_end[1]=100 ≥ 50 → True (the outer interval covers it). Query 5 → bisect_right=1, prefix_max_end[0]=100 ≥ 5 → True. Query 150 → prefix_max_end[1]=100 < 150 → False. Query -5 → bisect_right=0 → False. The prefix-max is what makes nested intervals work; checking only the largest start ≤ t would miss (0,100) for query 50.

Consequences: the failure mode and its tripwire. The failure is rebuilding the sorted array per update. Arithmetic: 10^6 intervals, 10^5 updates, rebuild each time = 10^5 × (10^6 log 10^6) ≈ 2×10^12 comparisons; at ~10^8 comparisons/s that is ~5.5 hours. The same 10^5 updates on an interval tree: 10^5 × log(10^6) ≈ 2×10^6 comparisons, ~0.02 s. (Hypothetical constants, but the ~10^6× gap is the point.)

So write the tripwire as a threshold the next owner can check without re-deriving anything: "if updates exceed 1% of queries, or p99 query latency exceeds the SLO, switch to TreeRangeSet." Include the benchmark that measures it and the command to run it.

Invariants to assert in tests. Static set: the array is sorted by low endpoint and never mutated after build; prefix_max_end is non-decreasing. Interval tree: it is a BST ordered by low endpoint, and each node's max equals the maximum high endpoint in its subtree. node.max == max(node.high, left.max, right.max). A property test that inserts random intervals and compares stabbing queries against a brute-force scan catches both the rebuild regression and a stale max before either reaches production.

Curated: · Written: · Reviewed:

Difficulty: Medium