KatInterview

Simulate a Least Recently Used Cache with Fixed Capacity

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

Last updated

Tests understanding of LRU eviction policy through hash map and doubly-linked list composition to achieve O(1) operations.

You are given a sequence of cache operations to simulate on a least recently used (LRU) cache with a fixed maximum capacity.

An LRU cache maintains key-value pairs and discards the least recently accessed entry when inserting a new key would exceed capacity. Both retrieval and insertion count as an access that updates recency.

Your task is to process a list of operations and return their results.

Operations

You will receive three parallel inputs:

  1. operations: a list of operation names, each either "get" or "put"
  2. arguments: a list of argument lists corresponding to each operation
  3. capacity: the maximum number of key-value pairs the cache can hold

Each operation behaves as follows:

  • get with argument [key]: if key exists in the cache, mark it as recently used and return its value; otherwise return None. This counts as an access.
  • put with arguments [key, value]: insert or update the key-value pair and mark it as recently used. If this insertion would exceed capacity and key is new, first remove the least recently used key. If capacity is zero, ignore all put operations. This counts as an access.

Return a list where each element corresponds to one operation: the returned value for get operations, or None for put operations.

Constraints

  • 1 ≤ len(operations) ≤ 10^4
  • operations[i] is either "get" or "put"
  • 0 ≤ capacity ≤ 10^4
  • All keys and values are integers
  • len(operations) == len(arguments)
  • Each arguments[i] has length 1 for "get" and length 2 for "put"

Examples

Example 1

Input: simulate_lru_cache(['put', 'put', 'get', 'put', 'get', 'get'], [[1, 10], [2, 20], [1], [3, 30], [2], [1]], 2)

Output: [None, None, 10, None, None, 10]

Example 2

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

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

Example 3

Input: simulate_lru_cache(['get', 'put', 'get', 'put', 'get'], [[5], [1, 100], [5], [2, 200], [1]], 0)

Output: [None, None, None, None, None]

Hints

Hint 1

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

Hint 2

A doubly-linked list can maintain access order efficiently if you can find and move nodes in O(1) time.

Hint 3

Store both the value and a reference to the list node in your hash map so you can reorder the list when a key is accessed.