TRT
Sign in
mediumCoreLeetCode#upper bound#hash map of sorted lists

Time based key-value store

Store values with timestamps and answer 'value as of time t' queries with an upper-bound search per key.

The Runtime Theory Team1 min read
Taught inLower and upper boundsPro — members onlyInstead of asking whether a value is present, ask where the first element that is at least x sits. That one question finds first and last occurrences, counts duplicates and gives insertion points, with no special cases.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inset(foo, bar, 1); get(foo, 1); get(foo, 3)

outbar, bar

inthen set(foo, bar2, 4); get(foo, 4); get(foo, 5)

outbar2, bar2

inget(foo, 0)

out""

Implement set(key, value, timestamp) and get(key, timestamp), where get returns the value set for the key at the largest timestamp less than or equal to the given one, or "" if there is none. Timestamps for each key arrive in increasing order.

Before you code

Because timestamps arrive in order, each key's history is already a sorted list: no sorting needed. A query is "last entry with timestamp ≤ t".

Hints

  1. Map each key to two parallel lists: timestamps and values.
  2. get: i = upper_bound(times, t) - 1. If i < 0, return "".
  3. Each operation is O(1) for set (append) and O(log n) for get.

Production & complexity notes

When solving Time based key-value store on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Lower and upper bounds to reinforce the underlying pattern.

What it practices

"Last element ≤ x" with an upper bound, from Lower and upper bounds.

Not started

Sign in to save your learning progress.

Sign in to save