Most asked top Interview Questions and Answers & Online Test
Education platform for interview prep, online tests, tutorials, and live practice

Build skills with focused learning paths, mock tests, and interview-ready content.

WithoutBook brings subject-wise interview questions, online practice tests, tutorials, and comparison guides into one responsive learning workspace.

Prepare Interview

Python Coding Interview Questions and Answers

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

Save For Revision

Bookmark this item, mark it difficult, or place it in a revision set.

Open My Learning Library
Is it helpful? Yes No

Most helpful rated by users:

Copyright © 2026, WithoutBook.