Search⌘ K
AI Features

Problem: LRU Cache

Explore the design and implementation of an LRU cache that supports constant-time get and put operations. Understand how combining a doubly linked list with a hash map enables efficient tracking of usage order and quick access of cached data. This lesson guides you through building the LRUCache class in Java, managing capacity, and handling eviction of least recently used items accurately.

Statement

Design a data structure that follows the constraints of a least recently used (LRU) cache.

Implement the LRUCache class with the following operations:

  • LRUCache(int capacity): Initializes the LRU cache with a positive size capacity.

  • int get(int key): Returns the value associated with key if it exists in the cache. Otherwise, returns 1-1.

  • void put(int key, int value): Updates the value of key if it already exists in the cache. Otherwise, inserts the key\-value pair into the cache. If this insertion causes the number of keys to exceed capacity, the least recently used key must be evicted.

Note: Both get and put must operate in O(1)O(1) average time complexity.

Constraints:

  • 11 \leq capacity 3000\leq 3000

  • 00 \leq key ...