Todas las publicaciones
post14 de abril de 2026

Implementación de Caché LRU

#javascript#map#cache#data-structures#algorithms
Hard⏱️ Logic Challenge
Implement an LRUCache class with get(key) and put(key, value) operations, both O(1). When capacity is exceeded, evict the least recently used item.
Ver solución
class LRUCache { constructor(capacity) { this.cap = capacity; this.map = new Map(); // JS Map maintains insertion order } get(key) { if (!this.map.has(key)) return -1; const val = this.map.get(key); this.map.delete(key); this.map.set(key, val); // move to end (most recent) return val; } put(key, value) { this.map.delete(key); this.map.set(key, value); if (this.map.size > this.cap) { this.map.delete(this.map.keys().next().value); // evict first = LRU } } } // Map.keys().next().value = the oldest inserted key. // Delete + re-insert on access moves item to 'most recent'.