LRU Cache

Medium Design Hash map Linked list

Problem

Design a cache with a fixed capacity that supports get and put in O(1) average time, and evicts the least recently used key when it is full. get returns -1 for a missing key. put updates the value if the key already exists.

Original: LeetCode 146: LRU Cache.

Examples

Example 1

Input`LRUCache: LRUCache(2), put(1, 1), put(2, 2), get(1), put(3, 3), get(2), put(4, 4), get(1), get(3), get(4)`
Output`[null, null, null, 1, null, -1, null, -1, 3, 4]`

Constraints

  • 1 <= capacity <= 3000
  • 0 <= key <= 10^4
  • 0 <= value <= 10^5
  • At most 2 * 10^5 calls will be made to get and put.

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (2)
  1. LeetCode 146: LRU Cacheleetcode.com
  2. Java SE 17 API: HashMapdocs.oracle.com