Expiring Store, Reversible Actions, and Org Chart Walk
Data Structure DesignModel answerLast updated
Three short design-and-code tasks: a key-value store with per-entry lifetimes and background pruning, an action history with undo/redo, and a depth-first walk over a hierarchy.
Answer all three parts. For each one, define a clean interface, write the core logic, and explain the time and space complexity.
Part 1: Key-value store with expiring entries
Build an in-memory store where every entry lives for a fixed number of seconds.
put(key, value, ttlSeconds)saves the value together with the moment it should stop being valid.get(key)returns the value if the key is present and still valid. Otherwise it returnsnull(or an equivalent "missing" result).- Begin with the simplest implementation that is correct.
Follow-up:
- Entries that expire but are never read again should still be removed eventually.
getis the hot path, so it must not do expensive housekeeping.- Assume a background worker or sidecar process can do the pruning. Which data structures should it use, and how does it cope with a key being overwritten?
- State the complexity of
put,get, and the pruning step.
Part 2: Reversible actions
Build a manager for actions that can be undone. Each action object has execute() and undo().
executeCommand(command)runs the action and records it in history only when the run succeeds.undo()reverts the most recent action that is still in effect.- Specify what happens when there is nothing to undo.
- Give time and space complexity.
Optional follow-up: add redo().
Part 3: Walking an org chart
An organization is a rooted tree. Each node has an id and zero or more children. Return the ids in depth-first order.
- Use either recursion or an explicit stack.
- Handle an empty tree.
- Give time and space complexity.
Hints
Hint 1
For the store, a hash map from key to (value, expiry) is enough for correctness if `get` compares the expiry with the current time. The heap is only needed to reclaim memory for keys nobody reads again.
Hint 2
A min-heap keyed by expiry time lets the pruner look only at the earliest deadlines. When a key is overwritten, the old heap record becomes outdated, so before deleting, check that the record's expiry matches what the map currently holds.
Hint 3
For undo/redo, think of two stacks: one for applied commands and one for undone commands. Decide what happens to the second stack when a brand-new command is executed, and what to do if `undo()` itself throws.
Hint 4
For the tree walk, an iterative version pushes children onto a stack in reverse order so the leftmost child is visited first. An empty input should produce an empty list.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Expiring store
Simplest correct version
Keep a hash map key -> (value, expires_at). On put, compute expires_at = now + ttl and overwrite the entry. On get, look the key up; if it is missing, or expires_at <= now, return null (and optionally delete that single entry, which is O(1)). Correctness depends only on this timestamp check, so it never depends on how often any cleanup runs.
The weakness is memory: a key that expires and is never read again stays in the map forever.
Pruning without slowing get
Add a min-heap of (expires_at, key) that put pushes into. A background pruner repeatedly looks at the top of the heap and pops while top.expires_at <= now. It never touches live entries.
The subtle point is overwrites. If a was stored for 10s and then re-stored for 100s, the heap still has the 10s record. Treat heap records as hints: after popping one, delete the key from the map only if the map's current expires_at equals the popped record's value. Otherwise the record is stale and is simply discarded. This guarantees a refreshed key is never removed early, and every live entry always has a heap record with its current expiry, so every expired entry is eventually reached.
Complexity
| Operation | Time | Notes |
|---|---|---|
put | O(log n) | map write plus heap push |
get | O(1) | map lookup plus one comparison |
| prune | O((k + s) log n) | k expired entries, s stale records popped |
Space is O(n + s). If the same keys are overwritten often, stale records accumulate; when the heap grows beyond roughly twice the map size, rebuild it from the map in O(n).
Alternatives and practical notes
- A timing wheel buckets keys by expiry second, giving O(1) insert and expiry at the cost of coarser timing.
- Random sampling of keys that have a TTL (as some production stores do) needs no extra index but is probabilistic.
- Use a monotonic clock so wall-clock changes cannot break expiry, and make the clock injectable for tests.
- If pruning runs on another thread, guard shared state with a lock and have the pruner work in small batches, releasing the lock between them so
getnever waits behind a long sweep.
Edge cases
ttl <= 0: either treat as already expired or reject; state the choice.- Reading exactly at
expires_at: treat as expired, and say so. - Overwriting a key replaces both the value and the expiry.
- If
nullcan be a legitimate stored value, use a sentinel to distinguish "absent" from "stored null".
import heapq, threading, time
class ExpiringStore:
def __init__(self, clock=time.monotonic):
self._clock = clock
self._data = {} # key -> (value, expires_at)
self._heap = [] # (expires_at, key), may hold stale records
self._lock = threading.Lock()
def put(self, key, value, ttl_seconds):
exp = self._clock() + ttl_seconds
with self._lock:
self._data[key] = (value, exp)
heapq.heappush(self._heap, (exp, key))
def get(self, key):
now = self._clock()
with self._lock:
entry = self._data.get(key)
if entry is None:
return None
value, exp = entry
if exp <= now:
del self._data[key]
return None
return value
def prune(self):
now = self._clock()
removed = 0
with self._lock:
while self._heap and self._heap[0][0] <= now:
exp, key = heapq.heappop(self._heap)
entry = self._data.get(key)
if entry is not None and entry[1] == exp:
del self._data[key]
removed += 1
if len(self._heap) > 2 * len(self._data) + 16:
self._heap = [(e, k) for k, (_, e) in self._data.items()]
heapq.heapify(self._heap)
return removed
Part 2: Reversible actions
Approach
Use two stacks: applied for commands that ran successfully and undone for commands that were reverted.
execute_command: callexecute()first; only if it does not raise, push ontoapplied. Then clearundone, because the old redo history no longer matches the current state.undo: ifappliedis empty, returnFalse. Otherwise callundo()on the top command; if that raises, leave history untouched and propagate the error. On success, move the command toundone.redo: the mirror image, moving fromundoneback toapplied.
Returning False for "nothing to undo" is sensible because it is a normal UI condition, not an error. Raising a dedicated exception is also fine if documented.
Complexity
Each operation is O(1) plus the cost of the command's own execute/undo. Clearing the redo stack costs O(r) but is amortized O(1) per command. Space is O(h) for history length h; cap it with a bounded deque if memory matters.
from collections import deque
class ActionHistory:
def __init__(self, max_history=None):
self._applied = deque(maxlen=max_history)
self._undone = []
def execute_command(self, cmd):
cmd.execute()
self._applied.append(cmd)
self._undone.clear()
def undo(self):
if not self._applied:
return False
cmd = self._applied[-1]
cmd.undo()
self._applied.pop()
self._undone.append(cmd)
return True
def redo(self):
if not self._undone:
return False
cmd = self._undone[-1]
cmd.execute()
self._undone.pop()
self._applied.append(cmd)
return True
Common mistakes: recording a command before it succeeds, forgetting to clear the redo stack after a new command, and popping before undo() succeeds.
Part 3: Depth-first walk
Return an empty list for an empty tree. Otherwise visit a node, then each child subtree in order.
Iterative version: push the root; pop a node, append its id, and push its children in reverse order so the first child is processed next.
def dfs_ids(root):
if root is None:
return []
out, stack = [], [root]
while stack:
node = stack.pop()
out.append(node.id)
for child in reversed(node.children):
stack.append(child)
return out
Complexity: time O(n), since each node is visited once. Space is O(h) for the stack on a balanced shape, but up to O(n) in the worst case (a very wide node pushes all its children at once, or a deep chain for the recursive version). The iterative form avoids recursion-depth limits on very deep hierarchies.