Time-based key-value store

Python data engineering interview problem. Difficulty: intermediate. Pattern: Binary Search. About 16 minutes. Part of the Pro drill bank.

Store key-value pairs with timestamps and retrieve the latest value stored at or before a given timestamp. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.

Implement a TimeMap class that stores key-value pairs at integer timestamps and retrieves values based on time lookups: set(key: str, val: str, ts: int) -> None: Stores the value val under key at timestamp ts. For any given key, timestamps are guaranteed to be provided in strictly ascending order across consecutive calls. get(key: str, ts: int) -> str: Returns the value associated with the largest timestamp less than or equal to ts. If no record exists for key at or before ts, return the empty string "".

Requirements

  • Return empty string when no record exists at or before the timestamp.
  • Support multiple keys independently.

Constraints

  • Timestamps are positive integers up to 10^7.
  • Calls to set for a single key arrive with strictly increasing timestamps.

Examples

Input: [tm := TimeMap(), tm.set('foo', 'bar', 1), tm.get('foo', 1)][-1] Output: 'bar' The exact timestamp 1 matches the stored record.

Topics: lakebench, python, bisect, timestamp-lookup.

More Python interview questions · All interview problems · Learn data engineering

intermediate

Time-based key-value store

Interview-style drill: Store key-value pairs with timestamps and retrieve the latest value stored at or before a given timestamp.

Implement a `TimeMap` class that stores key-value pairs at integer timestamps and retrieves values based on time lookups: - `set(key: str, val: str, ts: int) -> None`: Stores the value `val` under `key` at timestamp `ts`. For any given key, timestamps are guaranteed to be provided in strictly ascending order across consecutive calls. - `get(key: str, ts: int) -> str`: Returns the value associated with the largest timestamp less than or equal to `ts`. If no record exists for `key` at or before `ts`, return the empty string `""`.