Neural Mastery
← Practice
LRU Cache Operation Simulatormedium

LRU Cache Operation Simulator

medium Python for AI 15–20 min

NumPy allowed · plain Python earns 10 bonus points

Simulate an LRU cache eviction and access sequence preserving access recency ordering.

Related Skills

Task

Implement lru_cache_access(operations, capacity): simulate a fixed-capacity LRU cache. When capacity is exceeded during a put, evict the least recently accessed key. Return a list containing the return values of all get operations (-1 when key is not found).

Function Signature

lru_cache_access(operations: list[dict], capacity: int) -> list[any]

Examples

Example 1: Standard Put and Get Sequence
Input: operations = [{'op': 'put', 'key': 1, 'val': 10}, {'op': 'put', 'key': 2, 'val': 20}, {'op': 'get', 'key': 1}, {'op': 'put', 'key': 3, 'val': 30}, {'op': 'get', 'key': 2}, {'op': 'put', 'key': 4, 'val': 40}, {'op': 'get', 'key': 1}, {'op': 'get', 'key': 3}, {'op': 'get', 'key': 4}] capacity = 2
Output: [10, -1, -1, 30, 40]
Example 2: Capacity 1 Eviction
Input: operations = [{'op': 'put', 'key': 'a', 'val': 1}, {'op': 'get', 'key': 'a'}, {'op': 'put', 'key': 'b', 'val': 2}, {'op': 'get', 'key': 'a'}, {'op': 'get', 'key': 'b'}] capacity = 1
Output: [1, -1, 2]

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • Capacity is an integer >= 1.
  • Accessing a key via get or put refreshes its recency to most-recent.
Python3Saved ✓
def lru_cache_access(operations: list[dict], capacity: int) -> list[any]:
"""Simulate Least Recently Used (LRU) Cache operations.
Each op is {'op': 'get', 'key': k} or {'op': 'put', 'key': k, 'val': v}.
Return list of results for 'get' ops (-1 if key not present)."""
# Your implementation here
pass

Case 1: Standard Put and Get Sequence
Input: operations = [{'op': 'put', 'key': 1, 'val': 10}, {'op': 'put', 'key': 2, 'val': 20}, {'op': 'get', 'key': 1}, {'op': 'put', 'key': 3, 'val': 30}, {'op': 'get', 'key': 2}, {'op': 'put', 'key': 4, 'val': 40}, {'op': 'get', 'key': 1}, {'op': 'get', 'key': 3}, {'op': 'get', 'key': 4}] capacity = 2
Expected: [10, -1, -1, 30, 40]
Case 2: Capacity 1 Eviction
Input: operations = [{'op': 'put', 'key': 'a', 'val': 1}, {'op': 'get', 'key': 'a'}, {'op': 'put', 'key': 'b', 'val': 2}, {'op': 'get', 'key': 'a'}, {'op': 'get', 'key': 'b'}] capacity = 1
Expected: [1, -1, 2]