LRU Cache
Learn how to solve the 'LRU Cache' problem. This detailed resource details brute force and optimized approaches.
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 list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.