Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Question: Write a Python program to implement a simple LRU (Least Recently Used) cache.
Answer:

from collections import OrderedDict

class LRUCache:
 def __init__(self, capacity):
 self.cache = OrderedDict()
 self.capacity = capacity

 def get(self, key):
 if key in self.cache:
 self.cache.move_to_end(key)
 return self.cache[key]
 return -1

 def put(self, key, value):
 if len(self.cache) >= self.capacity:
 self.cache.popitem(last=False)
 self.cache[key] = value
 self.cache.move_to_end(key)

Example:

# Example usage:
lru_cache = LRUCache(3)
lru_cache.put(1, 1)
lru_cache.put(2, 2)
lru_cache.put(3, 3)
print(lru_cache.get(2))  # Output: 2
Is it helpful? Yes No

Most helpful rated by users:

©2025 WithoutBook