KatInterview

Replay Operations on a Bounded LRU Cache

Data Structure DesignAuto-graded · 22 test cases
MediumAuto-gradedData Structure Designcachelrueviction

Last updated

Tests understanding of least-recently-used eviction by executing a sequence of cache operations and collecting their return values.

You are given a sequence of operations to execute on a fixed-capacity cache with least-recently-used (LRU) eviction. Your task is to simulate these operations and return their results.

The cache stores string key-value pairs. When the cache reaches capacity and a new key is inserted, the least recently accessed key is evicted.

Input Format:

  • operations: list of operation names
  • arguments: parallel list of argument lists

Operations:

  1. "SecureCache" with [capacity]: Initialize or reset the cache to the given capacity. Returns None.
  2. "put" with [key, value]: Store or update a key-value pair. Returns None.
  3. "get" with [key]: Retrieve the value for the key. Returns the value string if found, otherwise None.

LRU Behavior:

  • Both get and put count as accessing a key, making it the most recently used.
  • When put is called on an existing key, update its value and mark it as most recently used. This does not trigger eviction.
  • When put inserts a new key and the cache is at capacity, evict the least recently used key first, then insert the new one.
  • get on a missing key returns None and does not affect cache state.
  • If capacity is 0 or negative, all put operations are ignored (cache remains empty).

Output Format: Return a list containing one result per operation:

  • "SecureCache" and "put": None
  • "get": the value string or None

Constraints:

  • 1 ≤ number of operations ≤ 1000
  • 0 ≤ capacity ≤ 100
  • Keys and values are non-empty strings with length ≤ 100
  • The first operation is always "SecureCache"

Examples

Example 1

Input: simulate_lru_cache(['SecureCache', 'put', 'put', 'get', 'put', 'get', 'get'], [[2], ['A', '123 Main'], ['B', '456 Oak'], ['A'], ['C', '789 Pine'], ['B'], ['C']])

Output: [None, None, None, '123 Main', None, None, '789 Pine']

Example 2

Input: simulate_lru_cache(['SecureCache', 'put', 'get', 'put', 'get'], [[1], ['home', '123 Main St'], ['home'], ['home', '456 Oak Ave'], ['home']])

Output: [None, None, '123 Main St', None, '456 Oak Ave']

Hints

Hint 1

OrderedDict tracks insertion order and provides move_to_end to reposition keys efficiently.

Hint 2

When updating an existing key with put, move it to most-recent position before checking capacity.

Hint 3

Eviction only happens when inserting a new key while at capacity—never when updating an existing key.