DIY: LRU Cache

Solve the interview question "LRU Cache" in this lesson.

Problem statement

Your task is to build an LRU(least recently used) cache. A cache is great for retrieving data efficiently, but its capacity is limited. You will build a structure that initializes a cache with a fixed capacity that allows read and write operations. When the cache reaches the maximum size, replace the least recent entry with the new one.

Coding exercise

You have to implement the functions Set(key, value) and Get(key). The function Set(key, value) takes key and value as parameters and assigns the value against the provided key. If the key already exists, it updates the value against that key. The function Get(key) takes key as a parameter and fetches the value that is stored against that key.

Sample input

lru = LRUCache(2) // Initialize the cache
lru.Set(10, 20) // Set the key 10 with value 20
lru.Get(10) // Get the value against key 10
lru.print() // Return the cached key-value pairs

Sample output

lru.Get(10) ==> 20  
lru.print() ==> "(10, 20)"

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.