mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2025-12-08 19:06:00 +00:00
* Add an example of the LRU Cache implementation. * Promote the node on set() as well. * Add LRU Cache images.
Least Recently Used (LRU) Cache
A Least Recently Used (LRU) Cache organizes items in order of use, allowing you to quickly identify which item hasn't been used for the longest amount of time.
Picture a clothes rack, where clothes are always hung up on one side. To find the least-recently used item, look at the item on the other end of the rack.
The problem statement
Implement the LRUCache class:
LRUCache(int capacity)Initialize the LRU cache with positive sizecapacity.int get(int key)Return the value of thekeyif thekeyexists, otherwise returnundefined.void set(int key, int value)Update the value of thekeyif thekeyexists. Otherwise, add thekey-valuepair to the cache. If the number of keys exceeds thecapacityfrom this operation, evict the least recently used key.
The functions get() and set() must each run in O(1) average time complexity.
Implementation
See the LRUCache implementation example in LRUCache.js. The solution uses a HashMap for fast O(1) cache items access, and a DoublyLinkedList for fast O(1) cache items promotions and eviction (to keep the maximum allowed cache capacity).
Made with okso.app
Costs
| Worst Case | |
|---|---|
| Space | O(n) |
| Get item | O(1) |
| Set item | O(1) |
