Medium Data Structures Advanced Structures
How would you implement an LRU (Least Recently Used) cache?
Answer
An LRU cache can be efficiently implemented using a combination of a hash map and a doubly linked list. The hash map provides O(1) access to cache entries, while the doubly linked list maintains the order of usage with most recently used at the head. On access, move the node to the head; on insertion when full, remove the tail node. This gives O(1) for both get and put operations.
IIT Certified
Master These Concepts with IIT Certification
175+ hours of industry projects. Get placed at Bosch, Tata Motors, L&T and 500+ companies.
Relevant for Roles
Software Engineer Backend Developer Systems Developer