Interview conceptSoftware Engineering Fundamentals

Cache And Versioned Data Structures

Asked of: Software Engineer

Last updated

Editorial comparison table matching four access patterns to their data structures, core invariant, and time guarantee: LRU, TTL cache, sliding-window maximum, and versioned array.

What's being tested

These problems test whether you can select the right data structure for a required access pattern, then state its time, space, and consistency guarantees precisely. The recurring themes are recency ordering, expiration, bounded domains, monotonicity, snapshots, and point-in-time lookup—each requiring more than choosing a familiar container. Amazon cares because production services must remain predictable under high request rates, memory pressure, concurrent access, failures, and rapidly changing data. Interviewers are probing whether you clarify semantics first, identify invariants, and design for edge cases instead of stopping at a superficially correct implementation.

Core knowledge

  • LRU eviction combines a hash map with a doubly linked list: map lookup is O(1)O(1), while removing or promoting an entry is O(1)O(1). Keep sentinel head/tail nodes to avoid special cases for empty, singleton, and full caches.

  • A TTL-aware cache must distinguish “expired on access” from “removed proactively.” Store an absolute expiration timestamp, reject expired entries during get, and use a min-heap keyed by expiry for cleanup rather than scanning all NN entries in O(N)O(N).

  • Expiration heaps accumulate stale heap records when a key is refreshed. Store a generation number or expiration value with each heap item; when popped, delete only if it still matches the map’s current record. Otherwise discard it in O(log⁡N)O(\log N).

  • Synchronization must protect the map, recency list, and expiration metadata as one invariant. A single mutex is easiest to prove correct; finer-grained locks may improve throughput but create lock-ordering, promotion, and cleanup races.

  • For “maximum of the last kk values,” use a monotonic decreasing deque of (index, value) pairs. Remove smaller values from the back, remove indices older than i−k+1i-k+1 from the front, and obtain the maximum from the front in amortized O(1)O(1) time.

  • A versioned array can store, for each index, a sorted history of (snapshot_id, value) changes. snap() increments a global identifier in O(1)O(1); set(i, v) appends or overwrites the current-version record; get(i, id) uses binary search in O(log⁡m)O(\log m).

  • Snapshot semantics must be explicit: decide whether multiple set calls to one index before snap() collapse into one record, whether reads before the first snapshot are valid, and whether snapshot IDs are globally increasing and contiguous.

  • A bounded integer universe supports direct addressing: maintain a boolean array or bitset indexed by value, giving expected and worst-case O(1)O(1) add, remove, and membership. Memory is O(U)O(U), so it is excellent for small dense universes but poor when UU is enormous and only a few values occur.

  • In a distributed cache, partition keys with consistent hashing or rendezvous hashing, replicate according to a stated failure model, and define behavior during node loss or rebalancing. Virtual nodes smooth load, but rebalancing can still create misses and backend bursts.

  • Cache invalidation needs a write ordering and failure policy. Cache-aside is simple—write the database, then invalidate—but stale reads and invalidation loss remain possible; versioned values, leases, or an outbox-based invalidation path can make behavior more explicit.

  • Capacity eviction and TTL expiration are separate policies: an item may be evicted while still fresh or remain resident after its TTL until lazy cleanup. Define whether expired entries count toward capacity and whether get refreshes recency, TTL, both, or neither.

Worked example

For Design a TTL-Aware LRU Cache Without Full Expiration Scans, a strong candidate first asks for the API, maximum capacity, TTL units, concurrency level, whether expired entries may be returned, and whether expiration must happen exactly at the deadline or merely before the next access. I would state assumptions such as get and put being thread-safe, expired values never being observable, and eviction being required when live capacity exceeds CC. I would organize the answer around four pillars: a hash map plus doubly linked list for LRU order, a min-heap for the next expiration, synchronized invariant maintenance, and lazy plus background cleanup. Each map entry would contain the value, absolute expiry time, list node, and possibly a generation counter to invalidate stale heap records. get would check expiry, remove expired entries, promote live entries to the list front, and return the value; put would update or insert, push a heap record, and evict from the list tail until capacity is restored. I would explicitly flag the tradeoff between one coarse-grained lock that is easy to reason about and sharded or read/write locking that improves concurrency but complicates consistency. I would also explain that a heap gives O(log⁡N)O(\log N) insertion and cleanup, while a timing wheel may provide cheaper high-volume expiration at the cost of granularity and implementation complexity. If I had more time, I would add metrics for hit rate, eviction reason, expired-item lag, heap size, and lock contention, then test concurrent refresh-versus-expire races.

A second angle

Versioned Integer Array with Snapshots and Point-in-Time Reads uses the same principle—retain only the history needed by the access pattern—but replaces recency and expiry with ordered versions. The key framing question is whether snapshots copy the entire array or merely define a timestamp at which later reads should interpret per-index histories. A full copy costs O(n)O(n) per snapshot and potentially O(nS)O(nS) space, while per-index change logs use space proportional to updates and binary search for historical reads. The subtle issue is collapsing repeated writes in the current snapshot and preserving the previous value when a new snapshot begins. This design generalizes to immutable data, MVCC-style reads, and audit histories without requiring every version to duplicate all state.

Common pitfalls

Analytical mistake: Treating TTL cleanup as a periodic full scan is correct functionally but violates the stated scalability requirement, producing O(N)O(N) cleanup work per sweep. A heap or timing wheel should be selected based on expiration precision, write rate, and cleanup volume.

Pitfall: Saying “the heap guarantees no expired item remains” is inaccurate; it guarantees efficient discovery of due records, while lazy expiration may leave expired entries physically stored until cleanup or access.

Communication mistake: Jumping straight to “use a hash map and linked list” without clarifying TTL semantics, duplicate updates, concurrency, or failure behavior makes an otherwise standard answer appear incomplete. State assumptions, then name the invariant each component maintains.

Pitfall: Claiming thread safety because individual map operations are atomic misses races across the map, list, and heap; those structures must be updated consistently.

Depth mistake: Giving only big-O notation without explaining constants and operational tradeoffs is weak for a system-oriented SWE discussion. For example, consistent hashing, replication, invalidation, and stampede prevention matter once the cache is distributed.

Pitfall: Assuming cache invalidation is always reliable; discuss stale reads, lost invalidation messages, write ordering, and what correctness guarantee the caller actually needs.

Connections

An interviewer may pivot to MVCC, immutable/persistent data structures, and event-sourced histories from versioned reads. Cache designs commonly lead to consistent hashing, cache stampede protection, leases, write-through versus cache-aside behavior, and observability for p99 latency and hit rate. Monotonic queues and direct addressing also connect to streaming algorithms and memory-performance tradeoffs.

Practice questions

Related concepts