KatInterview

Simulate a Bounded LRU Cache with Hit/Miss Tracking

Data Structure DesignAuto-graded · 15 test cases
EasyAuto-gradedData Structure Designdata structuressimulationcache

Last updated

Tests ability to simulate a sequence of GET/PUT operations on a capacity-bounded LRU cache and return accumulated hit/miss statistics.

Bounded LRU Cache Simulation

You are given a cache capacity and a list of operations to perform on an LRU (Least Recently Used) cache. Simulate the cache and return statistics about the run.

How the cache works

  • The cache holds at most capacity key-value pairs (both keys and values are non-negative integers).
  • PUT (key, value): Insert or update the entry for key.
    • If key already exists, update its value and mark it as most recently used.
    • If key does not exist and the cache is full, evict the least recently used entry first, then insert the new one.
  • GET (key): Look up key.
    • If found, mark it as most recently used and count it as a hit.
    • If not found, count it as a miss. The cache is unchanged.

Your task

Given capacity and operations, simulate all operations in order and return a dict with exactly three keys:

KeyValue
"hits"total number of GET hits
"misses"total number of GET misses
"final_cache"the contents of the cache after all operations, as a plain dict mapping each present key to its current value (order does not matter)

Input format

operations is a list of [op, key, value] triples where:

  • op is either "GET" or "PUT"
  • key and value are non-negative integers
  • For "GET" operations, value is always 0 (ignore it)

Constraints

  • 1 <= capacity <= 100
  • 1 <= len(operations) <= 2000
  • 0 <= key <= 1000
  • 0 <= value <= 10000
  • Every operation has op equal to "GET" or "PUT"
  • The cache starts empty.

Examples

Example 1

Input: simulate_lru_cache(2, [['PUT', 1, 10], ['PUT', 2, 20], ['GET', 1, 0], ['PUT', 3, 30], ['GET', 2, 0], ['GET', 1, 0]])

Output: {'hits': 2, 'misses': 1, 'final_cache': {'1': 10, '3': 30}}

Example 2

Input: simulate_lru_cache(3, [['PUT', 5, 50], ['GET', 5, 0], ['GET', 9, 0], ['PUT', 6, 60], ['PUT', 7, 70], ['PUT', 8, 80], ['GET', 5, 0], ['GET', 6, 0]])

Output: {'hits': 2, 'misses': 2, 'final_cache': {'6': 60, '7': 70, '8': 80}}

Example 3

Input: simulate_lru_cache(1, [['PUT', 1, 100], ['GET', 1, 0], ['PUT', 2, 200], ['GET', 1, 0], ['GET', 2, 0]])

Output: {'hits': 2, 'misses': 1, 'final_cache': {'2': 200}}

Hints

Hint 1

Use an OrderedDict from Python's collections module to track insertion/access order efficiently.

Hint 2

On every successful GET and every PUT (insert or update), move that key to the 'most recently used' end of the OrderedDict.

Hint 3

For the final_cache value, simply convert the OrderedDict to a plain dict before returning.