Skip to content

Instantly share code, notes, and snippets.

@sumitmallick
Created November 17, 2021 04:01
Show Gist options
  • Save sumitmallick/2ac3f9b6d823bee7e483031d9d920f9a to your computer and use it in GitHub Desktop.
Save sumitmallick/2ac3f9b6d823bee7e483031d9d920f9a to your computer and use it in GitHub Desktop.
# lru cache:
# Problem: Implement a LRU Cache:
# - 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.
from collections import OrderedDict
class LRU:
def __init__(self, capacity):
self.cache_dict = OrderedDict()
self.capacity = capacity
def get(self, key):
if key is not in self.cache_dict:
return -1
else:
self.cache_dict.move_to_end(key)
return self.cache_dict[key]
def put(self, key, value):
self.cache_dict[key] = value
self.cache_dict.move_to_end(key)
if len(self.cache_dict) > self.capacity:
self.cache_dict.popitem(last=False)
new_cache = LRU(10)
new_cache.put(3, 10) # O(1)
new_cache.get((3)) # 10 // O(1)
new_cache.get((6)) # -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment