⌘K
Flycodx

LRU Cache

LRU Cache

MediumSystem Design66% accepted

Design and simulate a Least Recently Used (LRU) cache with a given capacity. Implement two operations: - GET key: return the value if the key exists (and mark it as recently used), otherwise return -1 - PUT key value: insert or update the key-value pair. If the cache is at capacity, evict the least recently used key before inserting. Input format: - First line: two integers capacity and number of operations q - Next q lines: each line is either "GET key" or "PUT key value" Output: for each GET operation, print its result on a separate line.

Approach

Combine a hash map (key → node) with a doubly-linked list (most recent at head, LRU at tail). GET: move node to head, return value. PUT: if key exists update+move to head; if new, add at head and evict tail if over capacity.

Input

2 5 PUT 1 10 PUT 2 20 GET 1 PUT 3 30 GET 2

Output

10 -1
  • •1 ≤ capacity ≤ 3000, 0 ≤ key, value ≤ 10^4
solution.py
Loading editor...
Test 1
Test 2
Test 3

Press Run to test your custom input, or Submit to judge against all test cases.

Sign in to continue

Create a free account to run code, submit solutions and track progress.

  • Free forever — no credit card
  • 10+ languages with live execution
  • Points, streaks & leaderboards
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3