Scrivio Interview library
DesignAdvanced8 min read · updated 12 November 2026

You need an in-memory structure for interval queries: given 5 million time ranges for bookings, find all bookings overlapping a query range in under a millisecond. What structures would you consider, and how would you keep updates safe under concurrency?

The core structure is an interval tree: a balanced search tree keyed by start time where each node also stores the maximum end time in its subtree, so a query can skip every subtree that ends before the query range begins and find all k overlaps in roughly O(log n + k). A TreeMap keyed by start is simpler but degrades towards O(n) when intervals are long, and segment trees or bucketed time indexes suit fixed time grids. For concurrency, an immutable snapshot behind a volatile reference fits read-heavy loads, a ReadWriteLock or StampedLock fits frequent updates, and we should first check whether PostgreSQL range types with a GiST index already solve the problem.

Why this question is asked

Overlap queries show up in booking systems, calendars, pricing periods and resource scheduling: "which bookings touch 14:00 to 15:00 tomorrow?" With 5 million intervals and a sub-millisecond budget, a scan is out of the question, and the usual sorted map is not enough on its own. Interviewers ask this to see whether we know the right augmented structure, can reason about its cost, and can make it safe under concurrent updates. In this answer, we will define the overlap test, see why a sorted map by start falls short, build an interval tree, look at grid-based alternatives, handle concurrency, and consider letting the database do it.

1The Overlap Test

We treat each booking as a half-open interval [start, end): it includes its start and excludes its end, so a booking ending at 15:00 does not overlap one starting at 15:00. Two intervals [s1, e1) and [s2, e2) overlap exactly when s1 < e2 and s2 < e1. In words: each one starts before the other ends.

The difficulty is that the condition involves both ends. Sorting by start helps with the first half of the test, but says nothing about where intervals end.

2Why a TreeMap by Start Is Not Enough

A TreeMap<Long, List<Booking>> keyed by start time gives us headMap(queryEnd), every booking that starts before the query ends. We must then check each of those for end > queryStart. For a query late in the time line, headMap contains almost all 5 million bookings, and most of them ended long ago. So the scan is O(n) in the worst case, far too slow for one millisecond.

There is a useful trick when bookings have a known maximum duration D, say 24 hours: any overlapping booking must start after queryStart - D, so subMap(queryStart - D, queryEnd) bounds the scan. That works well for hotel nights or meeting rooms. But a single long booking, such as a 3-month reservation, breaks the bound, so we need a structure that handles any length.

3The Interval Tree: Augmenting With the Maximum End

An interval tree is a balanced binary search tree ordered by start time, where each node also stores maxEnd, the largest end time anywhere in its subtree. That one extra number lets the query prune. If a subtree's maxEnd is at or before queryStart, nothing in it can overlap, so we skip it entirely. And since the tree is ordered by start, once a node's start is at or after queryEnd, nothing in its right subtree can overlap either.

For a read-mostly snapshot, we do not need node objects. We sort the bookings by start into parallel arrays and treat the middle of each index range as the root of an implicit balanced tree, which keeps 5 million intervals in about 160 MB of primitive arrays.

Java
final class IntervalIndex {
private final long[] start, end, maxEnd, id; // sorted by start
IntervalIndex(long[] start, long[] end, long[] id) { // inputs already sorted by start
this.start = start; this.end = end; this.id = id;
this.maxEnd = new long[start.length];
build(0, start.length);
}
private long build(int lo, int hi) { // returns the max end in [lo, hi)
if (lo >= hi) return Long.MIN_VALUE;
int mid = (lo + hi) >>> 1;
long m = Math.max(end[mid], Math.max(build(lo, mid), build(mid + 1, hi)));
maxEnd[mid] = m;
return m;
}
void overlapping(long qs, long qe, LongConsumer out) { search(0, start.length, qs, qe, out); }
private void search(int lo, int hi, long qs, long qe, LongConsumer out) {
if (lo >= hi) return;
int mid = (lo + hi) >>> 1;
if (maxEnd[mid] <= qs) return; // whole subtree ends too early: skip it
search(lo, mid, qs, qe, out); // left side starts earlier, may overlap
if (start[mid] >= qe) return; // this and everything to the right start too late
if (end[mid] > qs) out.accept(id[mid]); // overlap test: start < qe and end > qs
search(mid + 1, hi, qs, qe, out);
}
}
// bookings [1,4) [2,3) [5,9) [6,7) with ids 10, 11, 12, 13
index.overlapping(3, 6, System.out::println); // 10, 12
Step throughSearching one subtree for overlaps with [qs, qe)
  1. Subtree's maxEnd <= qs?
    YesSkip the whole subtreeNoSearch the left half
  2. Node's start >= qe?
    YesStop: the node and its right side start too lateNoTest the node
  3. Node's end > qs?
    YesReport the bookingNoNot an overlap
  4. Search the right halfsame rules

4 steps in order. Play them, or step through them one at a time.

Notice that the recursion depth is only about log2(5,000,000), roughly 23 levels, so recursion is safe here. Building takes O(n log n) for the sort plus O(n) for maxEnd. The classic centered interval tree guarantees O(log n + k) for k results; this simpler augmented version visits a few extra nodes per result in the worst case, about O(k log n), and in practice queries that return a few dozen bookings touch only a few hundred array slots, well under a millisecond.

4Grid-Based Alternatives: Segment Trees and Time Buckets

If time is naturally divided into slots, such as 15-minute slots over a year, a grid structure can be simpler. A bucketed time index keeps, for each hour or day, the list of booking ids that touch it. A query looks at the buckets covering its range and removes duplicates. Lookups are very fast when bookings are short, but a long booking appears in many buckets, which costs memory, and queries need deduplication.

A segment tree is a tree over a fixed range of slots where each node covers an interval of slots and stores the bookings that cover it completely. It answers "which bookings cover this slot" and counting queries such as "how many rooms are booked at each slot" efficiently. Both suit fixed grids; the interval tree suits arbitrary start and end times.

5Keeping Updates Safe Under Concurrency

The array-based index is immutable, so for read-heavy loads with occasional updates we use copy-on-write snapshots: rebuild the index off to the side, every few seconds or on each batch of changes, and publish it by assigning a volatile field. Readers always see one complete, consistent snapshot without any locking. Rebuilding 5 million entries takes on the order of a second, so recent changes can be held in a small overlay list that queries also check until the next rebuild.

If updates are frequent and must be visible at once, a mutable node-based interval tree guarded by a lock is the alternative. A ReentrantReadWriteLock lets many readers in at once and gives a writer exclusive access. A StampedLock goes further with optimistic reads: a reader takes a stamp, reads without blocking, and then validates the stamp, retrying under a real read lock only if a write happened in between. That suits many fast readers and few writers, but optimistic reads of a mutable tree must tolerate seeing inconsistent state before validation, which makes the code harder to get right.

6Could the Database Do This Instead?

Before writing custom code, we should check whether the database already solves it. PostgreSQL has range types such as tstzrange, an overlap operator &&, and GiST indexes that answer overlap queries efficiently. It can even prevent double bookings with an exclusion constraint.

SQL
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE booking (
id bigint PRIMARY KEY,
room_id bigint NOT NULL,
during tstzrange NOT NULL,
EXCLUDE USING gist (room_id WITH =, during WITH &&) -- no overlapping bookings per room
);
CREATE INDEX booking_during ON booking USING gist (during);
SELECT id FROM booking
WHERE during && tstzrange('2026-11-06 14:00+00', '2026-11-06 15:00+00');

A well-indexed overlap query usually returns in a millisecond or a few, though the network round trip adds to that. If the sub-millisecond requirement is for in-process work at very high request rates, the in-memory index is justified, with the database still as the source of truth and the guard against overlaps.

7Follow-up questions

How would you count overlaps instead of listing them?

If we only need counts per time slot, a sweep over sorted start and end events, or a segment tree with counts, answers it without listing every booking. For a single query range, counting with the interval tree still visits each overlapping booking; a count-specific structure is faster when counts are all we need.

What if intervals are added and removed constantly?

Then rebuilding a snapshot each time is wasteful. A node-based balanced interval tree, for example a red-black tree augmented with maxEnd, updates in O(log n), maintaining maxEnd along the path and during rotations. We guard it with a read-write lock or partition it, for example by room, so writers contend less.

Why half-open intervals?

Because back-to-back bookings, one ending at 15:00 and the next starting at 15:00, should not count as overlapping, and half-open intervals make that fall out naturally from start < otherEnd and otherStart < end. PostgreSQL's default range bounds are also inclusive start and exclusive end.

8Conclusion

In this answer, we saw that overlap means each interval starts before the other ends, so sorting by start alone is not enough: a TreeMap by start scans towards O(n) unless durations are bounded. An interval tree augmented with the maximum end per subtree prunes whole subtrees and finds k overlaps in about O(log n + k), and can be stored compactly in sorted arrays. Segment trees and time buckets suit fixed grids. Immutable snapshots behind a volatile reference suit read-heavy loads, ReadWriteLock or StampedLock suit frequent updates, and PostgreSQL range types with GiST indexes and exclusion constraints may solve the whole problem without custom code.

What to say in the interviewAbout 90 seconds aloud

Open with

Two half-open intervals overlap when each starts before the other ends, so the query needs both ends. A TreeMap keyed by start lets me take everything starting before the query end, but then I scan all of those for end after the query start, which is O(n) for queries late in the timeline, unless I know a maximum duration and can bound the scan.

Then, if they want more

The right structure is an interval tree: a balanced tree ordered by start where each node stores the maximum end in its subtree.

During a query I skip any subtree whose max end is before the query start, and I stop going right once starts are past the query end, so I find k overlaps in about log n plus k.

For 5 million read-mostly bookings I would build it as sorted primitive arrays with an implicit balanced tree, about 160 MB, which answers typical queries in microseconds. If time is a fixed grid, a segment tree or hourly buckets are alternatives.

For concurrency, with mostly reads I would rebuild snapshots and swap a volatile reference, maybe with a small overlay of recent changes; with frequent updates, a node-based tree under a ReadWriteLock or StampedLock.

But first I would ask whether PostgreSQL can do it: a tstzrange column with a GiST index answers overlap queries quickly, and an exclusion constraint prevents double bookings.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "You need an in-memory structure for interval queries: given 5 million time ranges for...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/4afa645784/