Question bank

Design a data structure for a Least Recently Used (LRU) cache that efficiently supports 'get' and 'put' operations

February 4, 2025Updated March 31, 20263 min read
HardTechnicalData Structure DesignAlgorithm OptimizationPerformance EfficiencySoftware EngineerData Engineer
Design a data structure for a Least Recently Used (LRU) cache that efficiently supports 'get' and 'put' operations

Approach To design a data structure for a Least Recently Used (LRU) cache that efficiently supports get and put operations, follow this structured framework: Understand LRU Cache Requirements : It should store a limited number of items. When the cache…

Approach

To design a data structure for a Least Recently Used (LRU) cache that efficiently supports get and put operations, follow this structured framework:

  1. Understand LRU Cache Requirements:
  • It should store a limited number of items.
  • When the cache reaches its capacity, it should remove the least recently used item.
  • Choose Appropriate Data Structures:
  • Use a Hash Map for O(1) access time to cache items.
  • Use a Doubly Linked List to maintain the order of usage, allowing quick updates when items are accessed or added.
  • Implement Operations:
  • Define the get operation to retrieve items and move them to the front of the usage list.
  • Define the put operation to add items, evicting the least recently used item if necessary.

Key Points

  • Efficiency: Both get and put operations should run in O(1) time complexity.
  • Storage: The cache should have a fixed capacity that can be set upon initialization.
  • Order Maintenance: The order of items in the cache should be updated to reflect usage, with the most recently accessed items at the front.

Standard Response

Here's a sample implementation of an LRU Cache in Python using a hash map and a doubly linked list:

class Node:
 def __init__(self, key=0, value=0):
 self.key = key
 self.value = value
 self.prev = None
 self.next = None

class LRUCache:
 def __init__(self, capacity: int):
 self.capacity = capacity
 self.cache = {} # key -> Node
 self.head = Node() # Dummy head
 self.tail = Node() # Dummy tail
 self.head.next = self.tail
 self.tail.prev = self.head

 def _remove(self, node: Node):
 """Remove a node from the linked list."""
 prev_node = node.prev
 next_node = node.next
 prev_node.next = next_node
 next_node.prev = prev_node

 def _add_to_front(self, node: Node):
 """Add a node right after the head."""
 node.prev = self.head
 node.next = self.head.next
 self.head.next.prev = node
 self.head.next = node

 def get(self, key: int) -> int:
 """Return the value of the key if the key exists, otherwise return -1."""
 if key in self.cache:
 node = self.cache[key]
 self._remove(node)
 self._add_to_front(node)
 return node.value
 return -1

 def put(self, key: int, value: int) -> None:
 """Update the value of the key if the key exists. Otherwise, add the key-value pair."""
 if key in self.cache:
 node = self.cache[key]
 self._remove(node)
 node.value = value
 self._add_to_front(node)
 else:
 if len(self.cache) == self.capacity:
 # Remove the least recently used item (the last node)
 lru_node = self.tail.prev
 self._remove(lru_node)
 del self.cache[lru_node.key]
 new_node = Node(key, value)
 self.cache[key] = new_node
 self._add_to_front(new_node)

Tips & Variations

Common Mistakes to Avoid

  • Ignoring Capacity: Failing to implement eviction logic when the cache is full.
  • Inefficient Data Structures: Using lists for storage can lead to O(n) access times.
  • Not Handling Edge Cases: Forgetting to handle cases where get is called for a non-existent key.

Alternative Ways to Answer

  • For a technical role: Focus on the algorithmic complexity and discuss trade-offs of different data structures.
  • For a managerial role: Emphasize how this design can be scaled or modified for larger systems and discuss potential use cases.

Role-Specific Variations

  • Technical Positions: Discuss the time complexity in-depth and consider alternative implementations (e.g., using only a list).
  • Creative Roles: Relate the LRU cache concept to user experience, explaining how efficient data retrieval can enhance application performance.

Follow-Up Questions

  • How would you modify the cache to support concurrency?
  • What would be the impact of changing the data structure used for the cache?
  • Can you explain how you would test this implementation for edge cases?

By following this structured approach, job seekers can craft comprehensive and effective responses to interview questions about designing data structures, such as an LRU cache. This response not only demonstrates technical ability but

VA

Verve AI Editorial Team

Question Bank

Related reads

Explore More Question Bank Entries

What is brand management, and why is it important?
February 5, 2025Easy

What is brand management, and why is it important?

Approach To answer the question, "What is brand management, and why is it important?", it's crucial to adopt a structured framework that highlights your understanding of the concept and its significance in the business landscape. This can be broken down into…

Read answer guide
What is content marketing, and why is it important for businesses?
January 31, 2025Easy

What is content marketing, and why is it important for businesses?

Approach To effectively answer the question, "What is content marketing, and why is it important for businesses?", follow this structured framework: Define Content Marketing : Start with a clear definition. Explain Its Purpose : Discuss the primary goals of…

Read answer guide
What is cost accountancy?
February 10, 2025Easy

What is cost accountancy?

Approach To answer the question "What is cost accountancy?" effectively, follow this structured framework: Define Cost Accountancy : Start with a clear and concise definition. Explain Its Importance : Discuss why cost accountancy is vital for businesses.…

Read answer guide
What is cross-channel marketing, and why is it essential for business success?
February 2, 2025Medium

What is cross-channel marketing, and why is it essential for business success?

Approach When answering the question, "What is cross-channel marketing, and why is it essential for business success?" , it's important to structure your response effectively. Here’s a framework to guide you: Define Cross-Channel Marketing : Start by…

Read answer guide
What is cross-validation, and what is its purpose in model evaluation?
January 20, 2025Medium

What is cross-validation, and what is its purpose in model evaluation?

Approach To effectively answer the question “What is cross-validation, and what is its purpose in model evaluation?” , follow this structured framework: Define Cross-Validation : Clearly explain what cross-validation is in the context of machine learning.…

Read answer guide
What is customer segmentation and why is it important?
January 24, 2025Easy

What is customer segmentation and why is it important?

Approach Understanding customer segmentation is crucial for businesses aiming to maximize their marketing efforts and improve customer satisfaction. Here’s a structured framework to effectively answer the question, “What is customer segmentation and why is…

Read answer guide
What is data cleaning, and why is it important in data analysis?
January 5, 2025Easy

What is data cleaning, and why is it important in data analysis?

Approach When answering the question, "What is data cleaning, and why is it important in data analysis?", it’s essential to provide a structured response that not only defines data cleaning but also emphasizes its significance in the broader context of data…

Read answer guide
What is Data Wrangling, and why is it important in data analysis?
February 10, 2025Easy

What is Data Wrangling, and why is it important in data analysis?

Approach When answering the question "What is Data Wrangling, and why is it important in data analysis?", it's essential to provide a clear and structured response that showcases your understanding of the concept. Follow this framework: Define Data Wrangling…

Read answer guide
What is a Database Management System (DBMS)?
January 28, 2025Easy

What is a Database Management System (DBMS)?

Approach To effectively answer the question, "What is a Database Management System (DBMS)?", follow this structured framework: Define the DBMS : Start with a clear and concise definition. Explain the Purpose : Discuss why a DBMS is essential in managing…

Read answer guide