From c1ffafab0fab37e079a8b1937e6d4074401f2c3e Mon Sep 17 00:00:00 2001 From: Rui Hu <8199515+logreg-n-coffee@users.noreply.github.com> Date: Wed, 20 Dec 2023 00:05:49 -0700 Subject: [PATCH] Add Python solution to Q 52 --- code/52-least-recently-used-cache.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 code/52-least-recently-used-cache.py diff --git a/code/52-least-recently-used-cache.py b/code/52-least-recently-used-cache.py new file mode 100644 index 0000000..a65d821 --- /dev/null +++ b/code/52-least-recently-used-cache.py @@ -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)