LRU cache with capacity eviction

seniorjava · AI-on
  1. 1Restate the problem in one line
  2. 2Sketch the data model yourself
  3. 3Ask AI for a skeleton ONLY
  4. 4Ask AI for a test plan ONLY
  5. 5Implement the core logic yourself
  6. 6Run the tests — verify, don't trust
  7. 7Ask AI for edge cases you missed
  8. 8Ask AI to review your code
  9. 9Make the final judgment yourself

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.

iThe deal with the pair partner

The AI is deliberately fallible — it gives hints, not solutions, and sometimes proposes wrong code. It cannot touch your editor. Paste what you choose, then Run. Anything AI-derived stays UNVERIFIED until your tests go green.

Self-check

  • get on a missing key returns -1 and does not insert anything
  • get refreshes recency so a just-read key survives the next eviction
  • put on an existing key updates the value without growing the size
  • eviction removes the least-recently-used key, not the oldest-inserted one
  • you stated the per-operation complexity you are aiming for (O(1) is the goal)
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
unverifiedEdited since last clean run — run to verify.

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

Pair partner (병신 모드 · 버그 잡기)

gpt-4o-mini

Ask for a skeleton or a test plan — not the answer. Then implement the core yourself and come back for edge cases. Remember: the partner is fallible. Verify everything by running it.

The partner sees your editor but cannot change it. Copy any suggestion in by hand, then Run to verify.

AI랑 먼저 페어하고 눌러