Skip to content

Commit

Permalink
Add Python solution to Q 52
Browse files Browse the repository at this point in the history
  • Loading branch information
logreg-n-coffee committed Dec 20, 2023
1 parent dd17800 commit c1ffafa
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions code/52-least-recently-used-cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from collections import OrderedDict


# O(1) time complexity: __init__, get, and put are O(1)
# O(n) space complexity: size of the cache
class LRUCache:
def __init__(self, capacity: int):
self.cache = OrderedDict() # cache to store key-value pairs
self.capacity = capacity # max capacity of cache

def get(self, key: int) -> int:
# if key is in the cache, move it to the end
if key in self.cache:
self.cache.move_to_end(key)
return self.cache[key]
return -1

def put(self, key: int, value: int) -> None:
# if key is in the cache, move it to the end
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
# if the cache is full, pop the first item (least recently used)
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)

0 comments on commit c1ffafa

Please sign in to comment.