Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added python code LRU cache #30

Merged
merged 1 commit into from
Dec 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions docs/linked-list/lru-cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ defaultValue="java"
values={[
{ label: 'Java', value: 'java', },
{ label: 'C++', value: 'cpp', },
{ label: 'Python', value: 'python', },
]
}>
<TabItem value="java">
Expand Down Expand Up @@ -238,6 +239,34 @@ private:
};
```

</TabItem>
<TabItem value="python">

```python
# LRU Cache
# OrderedDict
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = OrderedDict()

# Time Complexity: O(1)
def get(self, key):
if key in self.cache:
value = self.cache.pop(key)
self.cache[key] = value
return value
else: return -1

# Time Complexity: O(1)
def put(self, key, value):
if key in self.cache:
self.cache.pop(key)
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
```

</TabItem>
</Tabs>

Expand Down