How would you implement an LRU cache with expected constant-time get and put operations?
Interactive Practice Mode
Formulate your thoughts or take notes before revealing the model solution.
Saved automatically
Model Answer & Deep-Dive Explanation
Combine a hash map from keys to nodes with a doubly linked list ordered by recent use. On a hit, move the node to the most-recent end; on an update, change its value and move it. On insertion at capacity, remove the least-recent node from both structures. These operations are expected O(1) with ordinary hash-map assumptions. Handle capacity zero, overwrites, and missing keys explicitly. In concurrent code, protect the map and list as one invariant; independently locking each structure can leave them inconsistent.
Related Questions in Data Structures & Algorithms
How to detect a cycle in a Linked List using Floyd's Cycle-Finding Algorithm?
Intermediate level • 513 views
Explain the LRU (Least Recently Used) Cache architecture and how to implement it in O(1) time complexity.
Advanced level • 1 views
How do you design a Distributed API Rate Limiter and what algorithms are commonly employed?
Advanced level • 1 views
What is Dynamic Programming? Compare Memoization (Top-Down) with Tabulation (Bottom-Up) using the 0/1 Knapsack Problem.
Advanced level • 1 views
How do a stack and a queue differ, and where would each be useful?
Easy level • 1 views