Tap here to switch tabs
Problem
Ask
Submissions

Problem: Implement LRU Cache

med
30 min
Explore how to implement an LRU cache to manage data storage efficiently by evicting the least recently used items when the cache is full. This lesson teaches you how to initialize the cache, add or update entries, and retrieve values while handling capacity limits. Gain hands-on experience with this common caching algorithm crucial for performance optimization in software development.

Statement

Implement an LRU cache class with the following functions:

  • Init(capacity): Initializes an LRU cache with the capacity size.
  • Set(key, value): Adds a new key-value pair or updates an existing key with a new value.
  • Get(key): Returns the value of the key, or 1-1 if the key does not exist.

If the number of keys has reached the cache capacity, evict the least recently used key and then add the new key.

As caches use relatively expensive, faster memory, they are not designed to store very large data sets. Whenever the cache becomes full, we need to evict some data from it. There are several caching algorithms to implement a cache eviction policy. LRU is a very simple and commonly used algorithm. The core concept of the LRU algorithm is to evict the oldest data from the cache to accommodate more data.

Constraints:

  • 11 \leq capacity 3000\leq 3000
  • 00 \leq key 104\leq 10^4
  • 00 \leq value 105\leq 10^5
  • At most 10310^3 calls will be made to Set and Get.
Tap here to switch tabs
Problem
Ask
Submissions

Problem: Implement LRU Cache

med
30 min
Explore how to implement an LRU cache to manage data storage efficiently by evicting the least recently used items when the cache is full. This lesson teaches you how to initialize the cache, add or update entries, and retrieve values while handling capacity limits. Gain hands-on experience with this common caching algorithm crucial for performance optimization in software development.

Statement

Implement an LRU cache class with the following functions:

  • Init(capacity): Initializes an LRU cache with the capacity size.
  • Set(key, value): Adds a new key-value pair or updates an existing key with a new value.
  • Get(key): Returns the value of the key, or 1-1 if the key does not exist.

If the number of keys has reached the cache capacity, evict the least recently used key and then add the new key.

As caches use relatively expensive, faster memory, they are not designed to store very large data sets. Whenever the cache becomes full, we need to evict some data from it. There are several caching algorithms to implement a cache eviction policy. LRU is a very simple and commonly used algorithm. The core concept of the LRU algorithm is to evict the oldest data from the cache to accommodate more data.

Constraints:

  • 11 \leq capacity 3000\leq 3000
  • 00 \leq key 104\leq 10^4
  • 00 \leq value 105\leq 10^5
  • At most 10310^3 calls will be made to Set and Get.