This question evaluates competence in designing efficient cache mechanisms and mastery of data-structure strategies to support average O(1) get and put operations.
Design and implement a Least Recently Used (LRU) Cache that supports the following operations in average O(1) time.
Implement a class LRUCache with:
LRUCache(int capacity)
: Initialize the cache with a
positive
capacity.
int get(int key)
: Return the value of the key if it exists; otherwise return
-1
.
void put(int key, int value)
: Insert or update the value of the key.
get
and
put
.
If capacity = 2:
put(1, 1)
-> cache = {1=1}
put(2, 2)
-> cache = {1=1, 2=2}
get(1)
-> returns
1
, cache order becomes [2 (LRU), 1 (MRU)]
put(3, 3)
-> evicts key
2
, cache = {1=1, 3=3}
get(2)
-> returns
-1