Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- OrderedDict whill maintain the actual key and value and also the order.
- Once an element is accessed, push to the end and end will be considered the Recently used and start will be least used.
- same goes for put also.
- */
- from collections import OrderedDict
- class LRUCache:
- def __init__(self, capacity: int):
- self.capacity = capacity
- self.cache = OrderedDict() # maintains insertion order
- def get(self, key: int) -> int:
- if key not in self.cache:
- return -1
- self.cache.move_to_end(key) # mark as most recently used → O(1)
- return self.cache[key]
- def put(self, key: int, value: int) -> None:
- if key in self.cache:
- self.cache.move_to_end(key) # mark as most recently used → O(1)
- self.cache[key] = value
- if len(self.cache) > self.capacity:
- self.cache.popitem(last=False) # remove least recently used → O(1)
Advertisement
Add Comment
Please, Sign In to add comment