Quick interview answer
To implement an LRU cache, I will use a combination of a dictionary and a doubly linked list. This allows O(1) time complexity for both get and put operations by maintaining the order of usage efficiently.
First, understand the core idea
An LRU (Least Recently Used) cache is a data structure that stores a limited number of items and evicts the least recently accessed item when the limit is reached. The goal is to provide fast access to the most recently used items while efficiently managing memory.
To achieve O(1) time complexity for both get and put operations, we can use a combination of a hash map (to store key-value pairs) and a doubly linked list (to maintain the order of usage). The hash map allows for quick access to the items, while the doubly linked list allows us to efficiently remove the least recently used item.
Time and space complexity
The time complexity for both get and put operations is O(1) because we can access the hash map and update the linked list in constant time.
The space complexity is O(n), where n is the capacity of the cache. This is because we need to store up to n key-value pairs in the hash map and the linked list.
Steps to implement the LRU Cache
Define the
LRUCacheclass with an__init__method to initialize the cache's capacity, a hash map for storage, and a doubly linked list for order tracking.Implement the
getmethod to retrieve a value by key, updating the linked list to mark the key as recently used.Implement the
putmethod to add a new key-value pair, evicting the least recently used item if the cache exceeds its capacity.
LRU Cache Implementation in Python
How this code works
In this implementation, we define a Node class to represent each entry in the doubly linked list. The LRUCache class initializes the cache with a specified capacity and sets up a head and tail node for the linked list.
The _remove method detaches a node from the linked list, while _add_to_front adds a node right after the head, marking it as recently used. The get method checks if the key exists; if it does, it retrieves the value, removes the node from its current position, and adds it back to the front. The put method adds a new key-value pair or updates an existing one, evicting the least recently used node if necessary. This ensures that both operations run in O(1) time.
The expected output for `cache.get(1)` is `1`, and for `cache.get(2)` after adding a third item, it is `-1`.
LRU Cache Operations Flow
Loading diagram…
Different Approaches to Implementing LRU Cache
| Approach | Time Complexity | Space Complexity | Notes |
|---|---|---|---|
| Hash Map + Doubly Linked List | O(1) | O(n) | Optimal for both get and put operations. |
| Array + Linear Search | O(n) | O(n) | Inefficient for get and put operations due to linear search. |
| OrderedDict (Python specific) | O(1) | O(n) | Simpler implementation but less control over eviction logic. |
Common mistakes
- Forgetting to update the linked list when accessing a key in
get. - Not handling the case when the cache reaches its capacity correctly.
- Confusing the order of operations when evicting the least recently used item.
What interviewers look for
- Understanding of data structures and their complexities.
- Ability to explain the reasoning behind the chosen approach.
- Clarity in coding and handling edge cases.
Key takeaways
- An LRU cache efficiently manages memory by evicting the least recently used items.
- Combining a hash map with a doubly linked list allows for O(1) operations.
- Always consider edge cases and constraints when implementing data structures.