LRU Cache
Detailed guide and Python implementation for the 'LRU Cache' problem.
1. Concept Overview
The 'LRU Cache' problem is a key challenge in the Linked List section.
This implementation focuses on easy-level logic in Python.
We prioritize technical accuracy and code readability in our provided solutions.
2. Real-World Applications
3. Visual Intuition
Visualizing the logic flow for LRU Cache.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for LRU Cache carefully.
2. Formulate brute force
Draft a simple iterative solution.
3. Identify inefficiency
Look for redundant calculations.
4. Optimize search path
Use hashing or sorting to speed up the process.
5. Final Implementation
Clean up the code for production standards.
Problem Statement
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
Implement the LRUCache class:
- LRUCache(capacity: int) - Initialize the LRU cache with positive size capacity.
- get(key: int) -> int - Return the value of the key if the key exists, otherwise return -1.
- put(key: int, value: int) -> None - Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity, evict the least recently used key.
The get and put functions must each run in O(1) average time complexity.
Input is a list of operations and a list of arguments. Implement a function lruCache(operations: list, arguments: list) -> list that returns a list of results (None for constructor and put).
- •1 <= capacity <= 3000
- •0 <= key <= 10000
- •0 <= value <= 100000
- •At most 200000 calls will be made to get and put
Examples
["LRUCache","put","put","get","put","get","put","get","get","get"], [[2],[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]]
[None,None,None,1,None,-1,None,-1,3,4]
Cache capacity is 2. put(1,1), put(2,2), get(1) returns 1. put(3,3) evicts key 2. get(2) returns -1 (evicted). put(4,4) evicts key 1. get(1) returns -1, get(3) returns 3, get(4) returns 4.
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Interview Insights & Variations
Complexity Analysis Breakdown
Why Time: Directly evaluates all possibilities.
Why Space: Uses standard local memory.
Why Time: Optimized paths reduce total operations.
Why Space: May trade memory for speed.
Optimized Solution Python Code
Optimized Solution Python Code
class DNode:
def __init__(self, key=0, val=0):
self.key = key
self.val = val
self.prev = None
self.next = None
class LRUCacheOpt:
def __init__(self, capacity: int):
self.cap = capacity
self.cache = {}
self.left = DNode(0, 0)
self.right = DNode(0, 0)
self.left.next = self.right
self.right.prev = self.left
def _remove(self, node):
prev, nxt = node.prev, node.next
prev.next = nxt
nxt.prev = prev
def _insert(self, node):
prev, nxt = self.right.prev, self.right
prev.next = node
nxt.prev = node
node.prev = prev
node.next = nxt
def get(self, key: int) -> int:
if key in self.cache:
self._remove(self.cache[key])
self._insert(self.cache[key])
return self.cache[key].val
return -1
def put(self, key: int, value: int) -> None:
if key in self.cache:
self._remove(self.cache[key])
self.cache[key] = DNode(key, value)
self._insert(self.cache[key])
if len(self.cache) > self.cap:
lru = self.left.next
self._remove(lru)
del self.cache[lru.key]Brute Force Code (Spoiler Guarded)
Brute Force Code (Spoiler Guarded)
class LRUCacheBrute:
def __init__(self, capacity: int):
self.cap = capacity
self.cache = {}
self.usage = []
def get(self, key: int) -> int:
if key not in self.cache:
return -1
self.usage.remove(key)
self.usage.append(key)
return self.cache[key]
def put(self, key: int, value: int) -> None:
if key in self.cache:
self.usage.remove(key)
elif len(self.cache) >= self.cap:
lru = self.usage.pop(0)
del self.cache[lru]
self.cache[key] = value
self.usage.append(key)Algorithm Pattern Checklist
When dealing with Linked List data patterns.
Core Prerequisites
Revision Key Notes
Common Mistakes & Pitfalls
Related Questions
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.