-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
dd17800
commit c1ffafa
Showing
1 changed file
with
25 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |