LRU cache with capacity eviction

seniorjava · AI-off30:00
  1. 1Clarify
  2. 2Code
  3. 3Test
  4. 4Optimize
  5. 5Done

Problem

Implement a fixed-capacity LRU cache of int keys to int values. get(key) returns the value or -1 if absent and counts as a use. put(key, value) inserts or updates; when the cache is over capacity, evict the least-recently-used key. Both get and put must keep the most recently touched key safe from the next eviction.

1Your goal now — Clarify

Restate the problem in one sentence and list the edge cases — before writing any code.

Say your opening out loud to unlock coding

Then keep talking — restate the problem + the edge cases in your own words.

Let me make sure I understand the problem, then I'll walk through my approach.

checking microphone…

Self-check

Hints / what this doesn't test

This is an Opendoor-flavored applied problem: a small stateful component with an eviction policy, not a puzzle. Restate it before coding — "So get is a use that makes a key recent, put can overflow, and the thing I drop is the least-recently used entry — reads count, not just writes?"

What this problem does not test (say so out loud): thread safety, an access-ordered LinkedHashMap(.., true) with removeEldestEntry (a valid shortcut worth naming), TTL/time-based expiry, and generic key/value types are out of scope here — but a senior names that the get-refreshes-recency rule is the part most naive caches get wrong.

Solution.javaauto-runs ~0.8s after you pause

Tests

○ Not run yet — edit the code or press Run
  • hit
  • miss
  • evict_lru
  • kept_recent
  • + 2 hidden tests — revealed once the visible ones pass
Step 1 of 5: Clarify