Build a small Python cache class with put() and get() backed by a dict, returning None for missing keys. O(1) operations, tested in your browser.
The problem
Implement a Cache class:
put(key, value)stores the value (overwriting any existing one).get(key)returns the stored value, orNoneif the key is missing.
The test calls the methods in order and collects every return value (put returns None).
Examples
Example 1
Input
run_ops(Cache, [], [["put", "a", 100], ["put", "b", 200], ["get", "a"], ["get", "c"]])
Expected output
[None, None, 100, None]
Example 2
Input
run_ops(Cache, [], [["put", "a", 1], ["put", "a", 2], ["get", "a"]])
Expected output
[None, None, 2]
+ 2 hidden tests on Submit — instances don't share storage.
Edge cases to ask about
- Missing key
- Overwrite
- Two instances
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.
Pick both to reveal the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| List of (key, value) pairs | O(n) per op | O(n) | Scanning for every get. |
| bestDict-backed | O(1) per op | O(n) | Hash table lookups. |
Walkthrough of the optimal approach (try it yourself first)
A dict in self._data does all the work: assignment for put, .get() for get (which returns None for missing keys).
Creating the dict in __init__ — not as a class attribute — keeps two caches from sharing storage. That is what the hidden test checks.
Complexity: O(1) time, O(n) space. Each get/put is one dict operation (O(1) average); the cache holds n entries.
Reveal the reference solution
class Cache: def __init__(self): self._data = {} def put(self, key, value): self._data[key] = value def get(self, key): return self._data.get(key)
Follow-ups interviewers ask
- Add a capacity with LRU eviction (question 81).
- Add a time-to-live per key.
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Implement a Simple Key-Value Cache in Python?
The optimal solution runs in O(1) time and O(n) auxiliary space. Each get/put is one dict operation (O(1) average); the cache holds n entries.
What is the brute-force approach, and how do you optimise it?
List of (key, value) pairs: O(n) per op time, O(n) space. Scanning for every get. Dict-backed: O(1) per op time, O(n) space. Hash table lookups.
What follow-up questions do interviewers ask about Implement a Simple Key-Value Cache?
Add a capacity with LRU eviction (question 81). Add a time-to-live per key.
