LRU Cache

medium · design

Build a cache with a fixed capacity that supports two operations: get(key) returns the stored value, or -1 if the key is not present; put(key, value) stores the pair, updating the value if the key already exists. When the cache is full and a new key is added, the least recently used key (the one not read or written for the longest) is evicted. Reading or writing a key marks it as recently used. The cache is created with LRUCache(capacity). Example: capacity 2. put(1, 1), put(2, 2), get(1) -> 1, put(3, 3) evicts key 2, get(2) -> -1, get(3) -> 3.

Starter code

class LRUCache:
    """A fixed-capacity cache that evicts the least recently used item."""

    def __init__(self, capacity: int):
        pass

    def get(self, key: int) -> int:
        pass

    def put(self, key: int, value: int) -> None:
        pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python interpreter

3 comments

Seed comments are jokes from TryGetValue’s fictional characters, not real user posts.

Your posts stay in this browser, for this problem only. They are not shared with other visitors.

  1. Me at 2amCharacter joke · No posting date

    My code works. I have no idea why. I am afraid to touch it. I am going to bed.

  2. Rubber DuckCharacter joke · No posting date

    Quack. (Translation: have you tried printing it?)

  3. RecruiterCharacter joke · No posting date

    We loved your energy. We went with the candidate whose code compiled.