LRU Cache

00:00
Harddesignhash-maplinked-list

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.

Implement the LRUCache class:

  • LRUCache(capacity) Initialize the LRU cache with positive size capacity.
  • int get(key) Return the value of the key if it exists, otherwise return -1.
  • void put(key, value) Update the value of the key if it exists. Otherwise, add the key-value pair to the cache. If the capacity is exceeded, evict the least recently used key.

Examples

Input → {"commands":["LRUCache","put","put","get","put","get","put","get","get","get"],"args":[[2],[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]]}
Output → [null,null,null,1,null,-1,null,-1,3,4]
JavaScript