KatInterview

Simulate a Cache with Recency-Based Eviction

Data Structure DesignAuto-graded · 23 test cases
MediumAuto-gradedData Structure Designhash-maplinked-listcache

Last updated

Tests data structure design by building an in-memory cache that removes the least recently accessed entry when full.

Build a function that simulates an in-memory cache with a fixed capacity. When the cache reaches its limit and a new entry must be added, the entry that has gone the longest without being accessed is removed.

You are given:

  • capacity: a positive integer representing the maximum number of entries the cache can hold
  • operations: a list of operation names, each either "get" or "put"
  • arguments: a list of argument lists, where arguments[i] contains the arguments for operations[i]
    • For a "get" operation: [key]
    • For a "put" operation: [key, value]

Process each operation in sequence:

  • get(key): If the key exists in the cache, return its value and mark it as recently accessed. If the key does not exist, return -1.
  • put(key, value): Insert the key-value pair into the cache, or update the value if the key already exists. Either way, mark the key as recently accessed. If adding a new key would exceed the capacity, first remove the entry that has gone the longest without being accessed. Return None (or null in the output).

Return a list containing one result per operation: the retrieved value or -1 for each get, and None for each put.

Constraints

  • 1 ≤ capacity ≤ 10⁴
  • 1 ≤ len(operations) ≤ 10⁵
  • len(operations) == len(arguments)
  • All keys and values are integers in the range [-10⁶, 10⁶]
  • Each operation is either "get" or "put"
  • Both get and put operations must run in O(1) average time

Examples

Example 1

Input: simulate_recency_cache(2, ['put', 'put', 'get', 'put', 'get', 'get'], [[1, 1], [2, 2], [1], [3, 3], [2], [3]])

Output: [None, None, 1, None, -1, 3]

Example 2

Input: simulate_recency_cache(2, ['put', 'put', 'get', 'put', 'get', 'put', 'get', 'get', 'get'], [[1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]])

Output: [None, None, 1, None, -1, None, -1, 3, 4]

Example 3

Input: simulate_recency_cache(1, ['put', 'get', 'put', 'get'], [[7, 10], [7], [8, 20], [7]])

Output: [None, 10, None, -1]

Hints

Hint 1

A hash map gives O(1) key lookups, but how do you track which entry is least recently used?

Hint 2

A doubly linked list can maintain access order, with the oldest entry at one end and the newest at the other. When an entry is accessed, move it to the fresh end.

Hint 3

Python's OrderedDict combines a hash map with ordering. Removing and reinserting a key moves it to the end, and popitem(last=False) removes the oldest.