Skip to content

Commit c1ffafa

Browse files
Add Python solution to Q 52
1 parent dd17800 commit c1ffafa

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

code/52-least-recently-used-cache.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from collections import OrderedDict
2+
3+
4+
# O(1) time complexity: __init__, get, and put are O(1)
5+
# O(n) space complexity: size of the cache
6+
class LRUCache:
7+
def __init__(self, capacity: int):
8+
self.cache = OrderedDict() # cache to store key-value pairs
9+
self.capacity = capacity # max capacity of cache
10+
11+
def get(self, key: int) -> int:
12+
# if key is in the cache, move it to the end
13+
if key in self.cache:
14+
self.cache.move_to_end(key)
15+
return self.cache[key]
16+
return -1
17+
18+
def put(self, key: int, value: int) -> None:
19+
# if key is in the cache, move it to the end
20+
if key in self.cache:
21+
self.cache.move_to_end(key)
22+
self.cache[key] = value
23+
# if the cache is full, pop the first item (least recently used)
24+
if len(self.cache) > self.capacity:
25+
self.cache.popitem(last=False)

0 commit comments

Comments
 (0)