15 · Linked Lists

#146 LRU Cache

Mediumsolve on LeetCode ↗

frequently reported atAppleOracleSamsungByteDance / TikTokWalmartAdobe

the problem

In plain words

Design a cache with a fixed capacity. get(key) returns the value or -1. put(key, value) inserts or updates; if the cache is over capacity, evict the least recently used key. Both must run in O(1) average time.

in capacity 2: put(1,1), put(2,2), get(1), put(3,3), get(2), put(4,4), get(1), get(3), get(4)

out 1, -1, -1, 3, 4

put(3,3) evicts key 2 (key 1 was just used); put(4,4) evicts key 1.

  • 1 ≤ capacity ≤ 3000
  • 0 ≤ key ≤ 10⁴
  • 0 ≤ value ≤ 10⁵
  • At most 2·10⁵ calls to get and put

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

Design: implement every operation. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #707
      Design Linked List
      Mediumin Java OOP
    2. #641
      Design Circular Deque
      Mediumin Queues
    3. #705
      Design HashSet
      Easyin Java OOP
    4. #155
      Min Stack
      Mediumin Stacks