Algorithm-Day36-LRU-Cache-lc-146
π§© Problem Description
Design a data structure that follows the Least Recently Used (LRU) cache policy.
Implement the LRUCache class:
LRUCache(int capacity)initializes the cache with a positive sizecapacity.int get(int key)returns the value of the key if it exists, otherwise returns-1.void put(int key, int value)updates the value of the key. If the number of keys exceeds the capacity, evict the least recently used key.
π¬ Example
1 | Input: |
π‘ Intuition
To achieve O(1) time complexity for both get and put, use:
- A HashMap to store key β node
- A Doubly Linked List to track the usage order
- Most recently used at the front
- Least recently used at the end
When a key is accessed:
- Move it to the front of the list
When inserting: - If at capacity, remove the tail (least recently used)
π’ Java Code (Custom Doubly Linked List)
1 | class LRUCache { |
β± Time and Space Complexity
- Time Complexity:
get: O(1)put: O(1)
- Space Complexity: O(capacity)
π§ Summary
- Combines a HashMap (for O(1) access) and a Doubly Linked List (for O(1) insert/delete).
- A great example of system design + data structure synergy.
- Common interview favorite!
Know this one cold β itβs the basis for many real-world cache systems (like Redis, in-memory caching, etc.)