Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

You need to answer queries like "what was the configuration in effect at time t" and "all events between t1 and t2" for an in-memory store of a few million timestamped records that is mostly read and occasionally appended. Compare TreeMap, a sorted array with binary search, and ConcurrentSkipListMap.

For a mostly read store of a few million timestamped records, the best default is an immutable sorted snapshot, such as a primitive long array of timestamps with a parallel array of records, searched with binary search and replaced through a volatile reference when a batch of appends arrives. TreeMap gives the same O(log n) floor and range queries with a friendlier API but costs far more memory per entry and is not thread-safe. ConcurrentSkipListMap is the choice when writes are frequent and concurrent, at the price of even more memory and weakly consistent range views.

Why this question is asked

Time-indexed lookups appear everywhere: which price, configuration or feature flag was in effect at a given moment, and which events happened in a window. At a few million records, the choice of data structure decides whether the store fits comfortably in the heap and whether queries take nanoseconds or microseconds. Interviewers ask this to see whether we can compare data structures on more than big O, including memory, cache behaviour, concurrency and how the data changes over time. In this answer, we will turn the two queries into operations on sorted keys, look at each of the three options with rough numbers, see how to publish snapshots safely, handle duplicate timestamps, and make a recommendation.

1Turning the Queries Into Sorted-Key Operations

Both queries need the records sorted by timestamp. The question "what was the configuration in effect at time t" means: find the latest record whose timestamp is less than or equal to t. That is a floor search. The question "all events between t1 and t2" means: find the first record at or after t1, then walk forward until we pass t2. That is a ceiling search followed by a scan.

Any structure that keeps keys sorted and can find a floor or ceiling in O(log n) answers both queries. The three candidates all do this. Where they differ is memory per record, how well they use the CPU cache, how they behave with concurrent threads, and what an append costs.

2Option 1: TreeMap

TreeMap gives us floorEntry(t) for the first query and subMap(t1, true, t2, true) for the second, both O(log n) to find the start. The API is pleasant and the range view iterates in order without copying.

The costs are memory and concurrency. Each entry is a separate tree node object holding a key reference, a value reference, left, right and parent references and a colour flag, about 40 bytes with compressed references, plus a boxed Long key of about 16 bytes. So we pay roughly 56 bytes per record before counting the record itself. For 5 million records that is around 280 MB of structure. The nodes are scattered across the heap, so each step of a search is likely a cache miss. And TreeMap is not thread-safe: an append while another thread searches can corrupt the tree or make a reader loop, so we would need a lock around every access.

3Option 2: A Sorted Array With Binary Search

Here we keep a long[] of timestamps in ascending order and a parallel array of the records. Arrays.binarySearch finds a timestamp in O(log n). When the exact value is missing, it returns -(insertionPoint) - 1, and from the insertion point we derive both floor and ceiling.

Java
final class Snapshot {
final long[] times; // sorted ascending
final Config[] values; // values[i] belongs to times[i]
Snapshot(long[] times, Config[] values) { this.times = times; this.values = values; }
Config inEffectAt(long t) {
int i = Arrays.binarySearch(times, t);
if (i < 0) i = -i - 2; // insertion point - 1 is the floor
return i >= 0 ? values[i] : null; // null: t is before the first record
}
}
// times = {100, 200, 300}
// inEffectAt(250) -> binarySearch returns -3, i = 1, values[1] (time 200)
// inEffectAt(300) -> exact match, i = 2
// inEffectAt(50) -> binarySearch returns -1, i = -1, null

The timestamps cost exactly 8 bytes each, so 5 million of them take 40 MB, and the reference array adds about 20 MB. A binary search touches about 23 positions, and the last several fall in the same cache lines, so it is very fast. A range query is two searches and a loop over a contiguous slice.

But there is a catch: arrays do not grow in the middle. If appends always carry newer timestamps, we can add at the end, but the array must still be copied when it fills up, and a single append to a 5-million-element array is a large copy. The usual answer is batching: collect new records in a small buffer, and every few seconds or every few thousand records merge them into a new array.

4Option 3: ConcurrentSkipListMap

ConcurrentSkipListMap is a sorted map built from linked lists stacked in levels, where higher levels skip over more elements. It implements the same NavigableMap methods as TreeMap, with O(log n) expected cost, and it is lock-free for readers and safe for concurrent writers.

Its weakness is memory: each entry has a data node and, on average, extra index nodes, plus the boxed key, so it is usually heavier than TreeMap. Its range views are weakly consistent: iterating a subMap never throws ConcurrentModificationException, but it may or may not show records added during the iteration. For a store that is written all the time by many threads this is a good fit. For a store that is mostly read and rarely appended, we pay for concurrency we hardly use.

Comparing the three options for 5 million records
OptionStructure memoryReads under appendsAppend cost
TreeMapabout 280 MBneeds a lockO(log n)
Sorted long[] snapshotabout 60 MBlock-free via volatile swapcopy or batch merge
ConcurrentSkipListMapabout 300 MB or morelock-free, weakly consistentO(log n), concurrent
Rough figures with compressed references, excluding the records themselves. Measure with JOL for your own types.

5Publishing an Immutable Snapshot

For mostly read data, the simplest correct design is to never modify the structure that readers see. Readers read a volatile reference to the current Snapshot. A single writer builds a new Snapshot from the old arrays plus the new batch, then assigns it to the volatile field. The volatile write guarantees that any reader who sees the new reference also sees fully built arrays.

Java
private volatile Snapshot current = new Snapshot(new long[0], new Config[0]);
Config inEffectAt(long t) { return current.inEffectAt(t); } // no lock
synchronized void appendBatch(long[] newTimes, Config[] newValues) { // one writer at a time
Snapshot old = current;
current = Snapshot.merge(old, newTimes, newValues); // build a new array, then publish it
}

Readers never wait and never see a half-written array. A query that started on the old snapshot finishes on the old snapshot, which is a consistent view. The cost is the copy on each batch, which for 60 MB takes a few tens of milliseconds and produces garbage, so we batch appends rather than merging one record at a time.

6What About Duplicate Timestamps?

Two events can share a millisecond. A map keyed by timestamp alone would silently keep only the last one, because put replaces the value. We have two fixes. We can use a composite key, such as (timestamp, sequence number), compared by time and then by sequence, so every record has a unique key and order within a millisecond is preserved. Or we can store a list of records per timestamp. In the array design, duplicates are allowed naturally, but Arrays.binarySearch may land on any of the equal elements, so we write our own search that returns the first or last index of a run of equal timestamps, depending on the query.

7Follow-up questions

When would you pick TreeMap after all?

When the data set is small enough that memory does not matter, say a few thousand configuration changes, and access is single-threaded or already guarded by a lock. Its API is the clearest of the three, and floorEntry and subMap express the queries directly, so code is easier to read and review.

Why is the volatile snapshot approach safe without locks for readers?

Because the arrays are never modified after the snapshot is published. The Java memory model guarantees that writes made before a volatile write are visible to a thread that reads that volatile field and sees the new value. So a reader either sees the old complete snapshot or the new complete snapshot, never a mix.

8Conclusion

In this answer, we saw that both queries are floor and range searches over sorted timestamps. TreeMap answers them with a clean API but costs about 56 bytes of structure per record and needs a lock. A sorted primitive array is compact and cache friendly but needs copying or batching for appends. ConcurrentSkipListMap handles concurrent writes with weakly consistent views at the highest memory cost. For a mostly read store, an immutable sorted snapshot published through a volatile reference is simple and fast, and duplicate timestamps need a composite key or a list per key.

What to say in the interviewAbout 90 seconds aloud

Open with

Both queries are sorted-key operations: the configuration at time t is a floor search, and events between t1 and t2 are a ceiling search followed by a scan.

Then, if they want more

All three options do that in log n, so I would compare them on memory, concurrency and append cost.

TreeMap has floorKey and subMap, but every entry is a node object plus a boxed Long, roughly 56 bytes of overhead, so a few million records cost a few hundred megabytes, and it is not thread-safe, so I would need a lock.

A sorted long array of timestamps with a parallel array of values is about 12 bytes per record and very cache friendly; binary search gives the insertion point, from which I get the floor. Its weakness is appends, which need copying, so I would batch them.

ConcurrentSkipListMap allows concurrent reads and writes with expected log n cost and weakly consistent range views, but it uses even more memory. Since the store is mostly read and occasionally appended, I would publish an immutable sorted snapshot through a volatile reference: readers never lock, and a single writer merges each batch into a new snapshot and swaps it in.

I would also handle duplicate timestamps with a composite key of time and sequence, or a list per key.

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 documentation below. 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 to answer queries like "what was the configuration in effect at time t" and...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/5d54e606b2/