File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments