146. LRU Cache
Asked at 103Apple100Amazon88Meta79Microsoft78Bloomberg72Google57Nutanix100TikTok100Palo Alto Networks100ByteDance100Confluent95Nvidia93Adobe91Visa89MongoDB88NetApp79Cisco68Goldman Sachs65Zomato62EPAM Systems60Accenture54tcs42Infosys39Airwallex100AppFolio100Aurora100Moloco100Okta100Oracle100Rivian100ServiceNow100Snap100StackAdapt100Yahoo100Zenefits100eBay100smartnews100X97KLA94Walmart Labs93Samsung92razorpay90Navan90Twitch89Chewy89Harness89Rakuten88Verkada88Nokia87Roku87Qualcomm87Squarepoint Capital85BitGo84Shopify83Nordstrom83Verily83Docusign82Coupang82Squarespace81SAP81PayPal79SoFi79Arista Networks78Autodesk77Millennium76Intuit76Uber75Jane Street75Citadel74ZScaler73PhonePe72Morgan Stanley72Optiver71Rubrik71Cloudflare70Zoom70Shopee69Tesla68Intel66Wells Fargo65Siemens65Expedia65LinkedIn65Salesforce64Tripadvisor62Paytm61General Motors60Snowflake59Swiggy59Booking.com59Netflix58Yandex55Sprinklr54IBM50OpenAI49DE Shaw47Rippling46Flipkart43Atlassian42Zoho42Anduril41DoorDash36Capital One35
Problem
Design LRUCache(capacity): get(key) returns the value or −1 if absent; put(key, value) inserts or updates a key, and if that pushes the size over capacity, it evicts the least recently used key. Both must run in O(1) average time.
Example: capacity 2: put(1,1), put(2,2), get(1) → 1, put(3,3) evicts key 2, get(2) → −1
Constraints: up to 2·10⁵ calls.
Hash map from key to node of a doubly linked list ordered by recency. get moves the node to the front; put inserts at the front and evicts the node before the tail when over capacity. Sentinels (head, tail) remove edge cases. Python's OrderedDict packages exactly this.
Complexity: O(1) per operation.
class LRUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.od = OrderedDict() # hash map + doubly linked list in one
def get(self, key: int) -> int:
if key not in self.od:
return -1
self.od.move_to_end(key) # most recent at the end
return self.od[key]
def put(self, key: int, value: int) -> None:
self.od[key] = value
self.od.move_to_end(key)
if len(self.od) > self.cap:
self.od.popitem(last=False) # evict least recent
c = LRUCache(2)
c.put(1, 1); c.put(2, 2)
assert c.get(1) == 1
c.put(3, 3) # evicts 2
assert c.get(2) == -1
c.put(4, 4) # evicts 1
assert c.get(1) == -1 and c.get(3) == 3 and c.get(4) == 4
class LRUCache {
private static class Node { int key, val; Node prev, next; Node(int k, int v) { key = k; val = v; } }
private final int cap;
private final Map<Integer, Node> map = new HashMap<>();
private final Node head = new Node(0, 0), tail = new Node(0, 0); // head.next = most recent
public LRUCache(int capacity) {
cap = capacity;
head.next = tail;
tail.prev = head;
}
private void unlink(Node n) { n.prev.next = n.next; n.next.prev = n.prev; }
private void addFront(Node n) {
n.next = head.next; n.prev = head;
head.next.prev = n; head.next = n;
}
public int get(int key) {
Node n = map.get(key);
if (n == null) return -1;
unlink(n);
addFront(n);
return n.val;
}
public void put(int key, int value) {
Node n = map.get(key);
if (n != null) { n.val = value; unlink(n); addFront(n); return; }
n = new Node(key, value);
map.put(key, n);
addFront(n);
if (map.size() > cap) {
Node lru = tail.prev;
unlink(lru);
map.remove(lru.key);
}
}
}
type lruNode struct {
key, val int
prev, next *lruNode
}
type LRUCache struct {
cap int
nodes map[int]*lruNode
head, tail *lruNode // sentinels: head.next is the most recent, tail.prev the least
}
func Constructor(capacity int) LRUCache {
head, tail := &lruNode{}, &lruNode{}
head.next, tail.prev = tail, head
return LRUCache{cap: capacity, nodes: map[int]*lruNode{}, head: head, tail: tail}
}
func (this *LRUCache) unlink(n *lruNode) {
n.prev.next, n.next.prev = n.next, n.prev
}
func (this *LRUCache) pushFront(n *lruNode) {
n.prev, n.next = this.head, this.head.next
this.head.next.prev = n
this.head.next = n
}
func (this *LRUCache) Get(key int) int {
n, ok := this.nodes[key]
if !ok {
return -1
}
this.unlink(n) // used: move to the front
this.pushFront(n)
return n.val
}
func (this *LRUCache) Put(key int, value int) {
if n, ok := this.nodes[key]; ok {
n.val = value
this.unlink(n)
this.pushFront(n)
return
}
n := &lruNode{key: key, val: value}
this.nodes[key] = n
this.pushFront(n)
if len(this.nodes) > this.cap { // evict the least recently used
lru := this.tail.prev
this.unlink(lru)
delete(this.nodes, lru.key)
}
}