imashutosh51

LRU cache

Jul 31st, 2022 (edited)
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.93 KB | None | 0 0
  1. /*
  2. OrderedDict whill maintain the actual key and value and also the order.
  3. Once an element is accessed, push to the end and end will be considered the Recently used and start will be least used.
  4. same goes for put also.
  5. */
  6.  
  7. from collections import OrderedDict
  8. class LRUCache:
  9.     def __init__(self, capacity: int):
  10.         self.capacity = capacity
  11.         self.cache = OrderedDict()  # maintains insertion order
  12.  
  13.     def get(self, key: int) -> int:
  14.         if key not in self.cache:
  15.             return -1
  16.         self.cache.move_to_end(key)  # mark as most recently used → O(1)
  17.         return self.cache[key]
  18.  
  19.     def put(self, key: int, value: int) -> None:
  20.         if key in self.cache:
  21.             self.cache.move_to_end(key)  # mark as most recently used → O(1)
  22.         self.cache[key] = value
  23.         if len(self.cache) > self.capacity:
  24.             self.cache.popitem(last=False)  # remove least recently used → O(1)
  25.  
Advertisement
Add Comment
Please, Sign In to add comment