KatInterview

Time-Travel Key-Value Store with Point-in-Time Snapshots

Data Structure DesignModel answer
MediumModel answerData Structure Designhash-mapbinary-searchversioning

Last updated

Design a hash-map-backed store that records every write with an increasing timestamp, answers reads as of any past moment, and exports a frozen plain-map snapshot.

Time-Travel Key-Value Store

Build a generic class TimeTravelMap<K, V> that remembers the full write history of every key. It must answer "what was the value at moment T?" and export a point-in-time copy of everything it holds.

Operations

  • long put(K key, V value) Record value as the newest value for key. Return the timestamp of this write.

  • V get(K key) Return the most recent value stored for key, or null if the key has never been written.

  • V get(K key, long timestamp) Return the value that was current for key at timestamp. Concretely, pick the write with the largest write-timestamp t satisfying t <= timestamp. If no such write exists, return null.

  • Map<K, V> freeze(long timestamp) Return an ordinary, non-versioned hash map. For every key that had at least one write at or before timestamp, the map holds that key's value as of timestamp. Keys with no write by then are absent. Later calls to put must never alter a map that was already returned.

Assumptions

  • Timestamps returned by put are strictly increasing across successive calls (for example, from an internal counter).
  • Deletion is out of scope.
  • State any extra assumptions you make (complexity targets, thread safety) before coding.

Example

put("a", 10) -> 1
put("a", 20) -> 2
put("b", 7)  -> 3

get("a", 1)   == 10
get("a", 2)   == 20
get("a", 100) == 20
freeze(2)     == { "a": 20 }
freeze(3)     == { "a": 20, "b": 7 }

What to deliver

Explain your design, implement it, state the time and space complexity of each operation, and discuss edge cases and trade-offs.

Hints

Hint 1

Where do timestamps come from? If a single global counter produces them, think about what that implies for the order of writes within any one key's history.

Hint 2

For each key, keep its history as two parallel lists (timestamps and values) that you only ever append to. Which standard search lets you find the last timestamp that is <= a query time?

Hint 3

For freeze, apply the same 'as of' lookup to every key and include a key only if at least one of its writes qualifies. Build a brand-new map so later writes cannot leak into it.