...

/

Implement LRU Cache

Implement LRU Cache

Try to solve the LRU Cache cache problem.

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.

Examples

Understand the problem

Let’s take a moment to make sure you've correctly understood the problem. The quiz below helps you check if you're solving the correct problem:

Implement LRU Cache

1

Suppose we have a cache with a capacity of 4. It has the keys shown below. The keys are shown sorted by age - oldest at the top, newest at the bottom. What is the new state of the cache, if we set a new pair with the following inputs?

key = 15

value = 100

A)
B)
C)

D)

Question 1 of 30 attempted

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Note: Focus on setting the value and then getting the value.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in main.py in the following coding playground. You'll need the provided supporting code to implement your solution.

Press + to interact
Python
usercode > LRU_cache.py
# Definition for a Linked List node
# class LinkedListNode:
# def __init__(self, pair):
# self.second = pair[1]
# self.first = pair[0]
# self.pair = pair
# self.next = None
# self.prev = None
# We will use a linkedlist of a pair of integers
# where the first integer will be the key
# and the second integer will be the value
from linked_list import LinkedList
class LRUCache:
def __init__(self, capacity):
# Write your code here
pass
def get(self, key):
# Replace this placeholder return statement with your code
return -1
def set(self, key, value):
# Write your code here
pass
LRU Cache

Access this course and 1200+ top-rated courses and projects.