LRU Cache Simulator

exact_matchMediumby cg
simulationdp

Solutions

0

Completed

0

Best Score

--

Last 24h

0

Description

Implement a Least Recently Used (LRU) cache simulator. Process a sequence of 'put' and 'get' operations on a cache with a fixed capacity. When the cache is full and a new key is inserted, the least recently used key is evicted. A 'get' operation that finds the key counts as a hit; otherwise it's a miss (returns -1). A 'put' operation always returns null in the results array.

Input Specification

A JSON object with keys:
  "capacity": integer — max number of key-value pairs the cache can hold
  "operations": array of operations:
    ["put", key, value] — insert or update a key
    ["get", key] — retrieve value for key

Example: {"capacity": 2, "operations": [["put", 1, 1], ["get", 1]]}

Output Specification

A JSON object with keys:
  "results": array — null for each put, value (or -1 for miss) for each get
  "cache_state": object — final key-value pairs in the cache
  "hits": integer — number of successful get operations
  "misses": integer — number of failed get operations

Example: {"results": [null, 1], "cache_state": {"1": 1}, "hits": 1, "misses": 0}

Example Test Cases

Test Case 1

Input

{
  "capacity": 2,
  "operations": [
    ["put", 1, 1],
    ["put", 2, 2],
    ["get", 1],
    ["put", 3, 3],
    ["get", 2],
    ["get", 3]
  ]
}

Expected Output

{
  "hits": 2,
  "misses": 1,
  "results": [null, null, 1, null, -1, 3],
  "cache_state": { "1": 1, "3": 3 }
}

Test Case 2

Input

{
  "capacity": 2,
  "operations": [
    ["put", 1, 10],
    ["put", 2, 20],
    ["put", 1, 30],
    ["get", 1],
    ["get", 2]
  ]
}

Expected Output

{
  "hits": 2,
  "misses": 0,
  "results": [null, null, null, 30, 20],
  "cache_state": { "1": 30, "2": 20 }
}

Submit a Solution

Your code must define a solve(input) function. It will be sandboxed and benchmarked against all test cases (including hidden ones).

Python4 lines · 52 chars

Leaderboard

No solutions on the leaderboard yet.