Tags

  • AWS (7)
  • Apigee (3)
  • ArchLinux (5)
  • Array (6)
  • Backtracking (6)
  • BinarySearch (6)
  • C++ (19)
  • CI&CD (3)
  • Calculus (2)
  • DesignPattern (43)
  • DisasterRecovery (1)
  • Docker (8)
  • DynamicProgramming (20)
  • FileSystem (11)
  • Frontend (2)
  • FunctionalProgramming (1)
  • GCP (1)
  • Gentoo (6)
  • Git (15)
  • Golang (1)
  • Graph (10)
  • GraphQL (1)
  • Hardware (1)
  • Hash (1)
  • Kafka (1)
  • LinkedList (13)
  • Linux (27)
  • Lodash (2)
  • MacOS (3)
  • Makefile (1)
  • Map (5)
  • MathHistory (1)
  • MySQL (21)
  • Neovim (10)
  • Network (66)
  • Nginx (6)
  • Node.js (33)
  • OpenGL (6)
  • PriorityQueue (1)
  • ProgrammingLanguage (9)
  • Python (10)
  • RealAnalysis (20)
  • Recursion (3)
  • Redis (1)
  • RegularExpression (1)
  • Ruby (19)
  • SQLite (1)
  • Sentry (3)
  • Set (4)
  • Shell (3)
  • SoftwareEngineering (12)
  • Sorting (2)
  • Stack (4)
  • String (2)
  • SystemDesign (13)
  • Terraform (2)
  • Tree (24)
  • Trie (2)
  • TwoPointers (16)
  • TypeScript (3)
  • Ubuntu (4)
  • Home

    [LeetCode 146] LRU Cache

    Published Apr 07, 2022 [  LinkedList  ]

    Problem

    Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.

    Implement the LRUCache class:

    • LRUCache(int capacity) Initialize the LRU cache with positive size capacity.
    • int get(int key) Return the value of the key if the key exists, otherwise return -1.
    • void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.

    The functions get and put must each run in O(1) average time complexity.

    Example 1:

    Input
    ["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
    [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
    Output
    [null, null, null, 1, null, -1, null, -1, 3, 4]
    
    Explanation
    LRUCache lRUCache = new LRUCache(2);
    lRUCache.put(1, 1); // cache is {1=1}
    lRUCache.put(2, 2); // cache is {1=1, 2=2}
    lRUCache.get(1);    // return 1
    lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
    lRUCache.get(2);    // returns -1 (not found)
    lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
    lRUCache.get(1);    // return -1 (not found)
    lRUCache.get(3);    // return 3
    lRUCache.get(4);    // return 4
    

    Constraints:

    • 1 <= capacity <= 3000
    • 0 <= key <= 104
    • 0 <= value <= 10^5
    • At most 2 * 10^5 calls will be made to get and put.

    Thoughts

    • O(1) get requires HashMap.
    • LRU requires a way to keep track of LRU and remove it in O(1) time, Doubly Linked List.
    • The HashMap stores key to Node pointer

    TypeScript

    1

    // Doubly Linked List node that stores key, value
    class Node {
        key: number
        value: number;
        prev: Node = null
        next: Node = null;
        
        constructor(key, value){
            this.key = key;
            this.value = value;
        }
    }
    
    class LRUCache {
        private capacity: number
        // stores key to Node
        private cache;
        // left most node, least recently used
        private LRU: Node
        // right most node, most recently used
        private MRU: Node;
        
        constructor(capacity: number) {
            this.capacity = capacity;
            this.cache = {}
            this.LRU = new Node(0, 0)
            this.MRU = new Node(0, 0);
            this.LRU.next = this.MRU;
            this.MRU.prev = this.LRU;
        }
    
        // remove a node from list
        remove(node: Node){
            const next: Node = node.next, prev: Node = node.prev;
            
            prev.next = next;
            next.prev = prev;
        }
    
        // add a node before MRU
        add(node: Node){
            const prev: Node = this.MRU.prev, next: Node = this.MRU;
            
            prev.next = node;
            next.prev = node;
            node.prev = prev;
            node.next = next;
        }
    
        get(key: number): number {
            // if key exists in cache, update node & return the value
            if(key in this.cache){
                this.remove(this.cache[key])
                this.add(this.cache[key])
                return this.cache[key].value;
            }
            
            return -1;
        }
    
        put(key: number, value: number): void {
            // remove if exists
            if(key in this.cache){
                this.remove(this.cache[key])
            }
            // update cache & list
            this.cache[key] = new Node(key, value);
            this.add(this.cache[key])
    
            if(Object.keys(this.cache).length > this.capacity){
                const LRUNode: Node = this.LRU.next;
                this.remove(LRUNode)
                delete this.cache[LRUNode.key]
            }
        }
    }
    
    /**
     * Your LRUCache object will be instantiated and called as such:
     * var obj = new LRUCache(capacity)
     * var param_1 = obj.get(key)
     * obj.put(key,value)
     */
    

    2

    // Fortunately JS/TS has a very convenient structure called Map, which behaves like an object, with the particularity of respecting insertion order of keys. 
    // So we know if we add a key, it will be at the end of the object, and the first inserted key will be at the beginning.
    
    // The "key" (haha) is to be sure to remove keys and re-add it at the end of the map when interacted with.
    class LRUCache {
      capacity: number;
      map: Map<number, number>;
    
      constructor(capacity: number) {
          this.capacity = capacity;
          this.map = new Map();
      }
    
      get(key: number): number {
        const value = this.map.get(key);
    
        if (value === undefined) return -1;
              
        this.map.delete(key);
        this.map.set(key, value);
        
        return value;
      }
    
      put(key: number, value: number): void {
        // remove last element to avoid overflow, only if it does not have 
        // the inserted key is a new key
        if (this.map.size >= this.capacity && !this.map.has(key)) {
            const firstKey = this.map.keys().next().value;
            this.map.delete(firstKey);
        }
    
        this.map.delete(key);
        this.map.set(key, value);
      }
    }
    

    Reference