Skip to content

James Postadan | Oct2025-2 | Module Complexity | Sprint 2 | Implement an LRU cache in Python - #16

Open
japostadan wants to merge 1 commit into
mainfrom
issue-09-implement-lru-cache
Open

James Postadan | Oct2025-2 | Module Complexity | Sprint 2 | Implement an LRU cache in Python#16
japostadan wants to merge 1 commit into
mainfrom
issue-09-implement-lru-cache

Conversation

@japostadan

@japostadan japostadan commented Jun 17, 2026

Copy link
Copy Markdown
Owner

🎯 Summary

  • Implemented an LRU (Least Recently Used) cache in Python with O(1) get and set
  • LruCache(limit) — raises ValueError when limit is 0
  • get(key) — returns value or None; counts as a use and promotes entry to most-recent
  • set(key, value) — stores entry; updates and promotes if key exists; evicts least-recently-used when over limit

🧾 Changelist

  • Data structure: dict + doubly linked list. The dict maps key → Node for O(1) lookup. The doubly linked list tracks recency — head is most recently used, tail is least recently used. Both structures are needed: without the dict, finding a node by key is O(n); without the list, moving a node to the front or evicting the tail is O(n).
  • get: look up the node in the dict (O(1)), move it to the head of the list (O(1)), return its value.
  • set: if the key already exists, update the value and move the node to the head (O(1)). If new, create a node, push to head, add to dict — then if len(store) > limit, evict the tail: delete from dict by tail.key and unlink from list (all O(1)).
  • Internal list operations: _push_head, _unlink, _move_to_head, _evict_tail — each does only pointer reassignment, all O(1).

Questions

  • get returns None for a missing key. Should it raise a KeyError instead (dict-like behaviour), or is returning None the right API for a cache where misses are expected?

🙌 Notes for Reviewers

- LruCache(limit) raises ValueError for limit=0
- get(key): dict lookup O(1), move to head O(1), return value or None
- set(key, value): insert/update at head O(1), evict tail when over limit O(1)
- internal doubly linked list tracks recency (head=most recent, tail=least recent)
- _store dict maps key→Node for O(1) access; needed for O(1) eviction of tail by key
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant