KatInterview

Simulate a Fixed-Capacity Recency-Eviction Cache

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

Last updated

Tests whether you can combine a hash map and ordered structure to implement O(1) get/put with least-recently-used eviction on a bounded cache.

Fixed-Capacity Recency-Eviction Cache

You are building a simple in-memory cache that discards the entry used least recently whenever it runs out of room. Write a simulator that processes a sequence of named operations and returns the result of each one.

Operations

The simulator receives two parallel lists:

  • operations: a list of strings naming each operation.
  • arguments: a list of argument lists, one per operation.

The three possible operations are:

"LRUCache" with arguments = [capacity] Set up a fresh, empty cache with room for exactly capacity entries. Returns None.

"get" with arguments = [key] Look up key in the cache.

  • If key is present, return its associated value and mark it as the most recently used entry.
  • If key is absent, return -1. The cache is not modified.

"put" with arguments = [key, value] Insert or update an entry.

  • If key already exists, overwrite its value and mark the entry as most recently used.
  • If key is new, insert it as the most recently used entry. If this causes the number of entries to exceed capacity, remove the entry that was least recently used before this insertion.

Returns None.

Output

Return a list with one element per operation, preserving the original order. Operations that produce no value ("LRUCache" and "put") contribute None to the list.

Constraints

  • The first operation is always "LRUCache".
  • 1 <= capacity <= 3000
  • 0 <= key <= 10^4
  • 0 <= value <= 10^5
  • The total number of operations is at most 2 × 10^5.
  • All operation strings are exactly one of "LRUCache", "get", or "put".

Examples

Example 1

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

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

Example 2

Input: lru_cache_operations(['LRUCache', 'put', 'get', 'put', 'get', 'get'], [[1], [1, 10], [1], [1, 20], [1], [2]])

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

Hints

Hint 1

A plain dictionary gives O(1) key lookup but carries no ordering information. What extra structure could track which entry was touched least recently?

Hint 2

A doubly linked list lets you move any node to the front and remove the back node in O(1) — provided you already hold a direct pointer to that node. What gives you that pointer instantly for any key?

Hint 3

Python's collections.OrderedDict maintains insertion order and exposes move_to_end() and popitem(last=False), which map directly onto the recency operations you need.