Design and implement an in-memory cache that evicts entries using the Least Recently Used (LRU) policy.
The cache should store key–value pairs and support the following operations:
LRUCache(int capacity)
: Initialize the cache with a positive integer
capacity
representing the maximum number of key–value pairs it can hold.
int get(int key)
:
-1
.
void put(int key, int value)
:
capacity
, you must
evict exactly one key–value pair: the one that has been least recently used
(i.e., the one whose
get
or
put
was accessed furthest in the past).
Requirements:
get
and
put
operations must run in
O(1)
average time.
capacity >= 1
.
Describe the data structures you would use and then implement the LRU cache in a language of your choice.