KatInterview

Simulate a Time-To-Live (TTL) Key-Value Store

Data Structure DesignAuto-graded · 15 test cases
EasyAuto-gradedData Structure Designdesign-dshash-table

Last updated

Process a series of operations on an in-memory key-value store with fixed time-to-live expiration dynamics.

Design and simulate a key-value store where each entry has a fixed duration (time-to-live or TTL) before it expires.

When the store is initialized, it is assigned a fixed positive integer ttl. The store processes a sequence of operations in order. Each operation is specified by an operation name and a list of arguments:

  1. "put": Takes [key, value, now]. Inserts a new key-value pair or updates an existing one. The key's expiration timestamp is set to now + ttl. Returns None.
  2. "get": Takes [key, now]. Returns the value associated with key if the entry exists and has not expired at timestamp now. If the key does not exist or is expired, returns None. Note: an entry expires when expiry <= now (it remains strictly valid while expiry > now).
  3. "renew": Takes [key, now]. If the key exists and is not expired at timestamp now, updates its expiration timestamp to now + ttl (retaining its current value) and returns True. If the key is missing or expired, it cannot be renewed, and returns False.
  4. "count_live": Takes [now]. Returns the number of key-value pairs in the store that are still active/valid at timestamp now (i.e., expiry > now).

Given ttl, a list of string operations, and a corresponding list of argument lists arguments, execute all operations sequentially and return a list containing the output of each operation.

Constraints

  • ttl is a positive integer.
  • operations and arguments have equal length $N$ ($1 \le N \le 1000$).
  • operations[i] is one of "put", "get", "renew", or "count_live".
  • key is a string. value can be any standard primitive data type (string, integer, etc.).
  • now is a non-negative integer.
  • An entry is valid strictly when expiry > now. At the exact timestamp now = expiry, the entry is considered expired.

Examples

Example 1

Input: ttl_cache_operations(5, ['put', 'get', 'count_live', 'renew', 'get', 'count_live'], [['a', 1, 10], ['a', 14], [14], ['a', 14], ['a', 18], [19]])

Output: [None, 1, 1, True, 1, 0]

Example 2

Input: ttl_cache_operations(3, ['put', 'put', 'get', 'get', 'renew', 'count_live'], [['x', 'old', 1], ['x', 'new', 2], ['x', 4], ['x', 5], ['x', 5], [5]])

Output: [None, None, 'new', None, False, 0]