Build a Tree System with LRU Cache and Command History
Data Structure DesignModel answerLast updated
Design a data structure for a tree where nodes can be read, modified, and traversed, with an LRU cache for fast access and an undo stack for reverting changes.
You're designing a system to manage a tree-structured dataset where each node has a unique identifier and an integer value. The tree is defined by parent-child relationships, and you need to support efficient reads, writes with history, and subtree aggregation.
Operations
Implement a class that supports:
-
Caching with LRU eviction: Maintain a fixed-capacity cache (size
k) of recently accessed nodes. When the cache fills, remove the least recently used entry. -
Mutable values with undo: Allow updating any node's value. Each modification should be reversible—calling
undo()restores the value before the most recent change. -
Subtree traversal: Compute the sum of all values in a subtree rooted at a given node. As you visit each node during traversal, treat it as a cache access.
Interface
class TreeSystem:
def __init__(self, nodes, capacity):
"""
nodes: dict mapping node_id -> (value, parent_id)
parent_id is None for root nodes
capacity: maximum number of cached entries (k)
"""
pass
def get(self, node_id):
"""Return the value and mark as recently used"""
pass
def update(self, node_id, new_value):
"""Change the value and record for undo"""
pass
def undo(self):
"""Revert the most recent update; return True if successful, False if nothing to undo"""
pass
def get_subtree_sum(self, root_id):
"""Return sum of all values in the subtree; cache each visited node"""
pass
Constraints
- Up to 10⁵ nodes
- Cache capacity
1 ≤ k ≤ N - Node IDs are unique
- Values are integers
- Operations on unknown IDs should raise an error
Example
nodes = {1: (10, None), 2: (5, 1), 3: (3, 1)}
system = TreeSystem(nodes, capacity=2)
system.get(2) # returns 5, caches node 2
system.update(2, 20) # node 2 now has value 20
system.get_subtree_sum(1) # returns 10 + 20 + 3 = 33
system.undo() # node 2 reverts to 5
system.get_subtree_sum(1) # returns 10 + 5 + 3 = 18
Requirements
- All single-node operations should run in O(1) time
- The subtree sum should run in O(S) where S is the subtree size
- Cache and undo stack must remain consistent after all operations
Hints
Hint 1
Use a doubly-linked list with a hash map to implement constant-time LRU operations
Hint 2
Store the old value when updating so undo can restore it—this is the Command pattern
Hint 3
Build a parent-to-children map once during initialization to enable downward tree traversal
Hint 4
When updating or undoing, check if the node is cached and synchronize both the cache and the main store
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem combines three classic data structure patterns into one cohesive system. The key challenge is maintaining consistency across all three components.
Core Design
Use three separate but synchronized structures:
- Authoritative store: A dictionary mapping
node_id -> valueas the single source of truth - LRU cache: A hash map plus doubly-linked list for O(1) access and eviction
- Undo stack: A list of
(node_id, old_value)tuples for reverting changes
Additionally, precompute a children adjacency list from the parent pointers to enable efficient downward traversal.
LRU Cache Implementation
The classic LRU cache uses two data structures:
- Hash map from node ID to linked list node (O(1) lookup)
- Doubly-linked list ordered by recency (most recent at head, least recent at tail)
Use sentinel head and tail nodes to eliminate null checks. When accessing a node:
- If cached, unlink it from its current position
- Insert (or reinsert) at the head
- If over capacity, evict
tail.prev
Consistency Rules
The cache must never return stale data. Establish these invariants:
- Reads go through the cache:
get()checks the cache first, falls back to the store, then caches the result - Writes synchronize both:
update()andundo()modify the authoritative store and also update the cached copy if present - Writes don't affect recency: Modifying a value doesn't move it in the LRU order (only reads count as "use")
Undo Mechanism
Each update() pushes the previous value onto a stack before applying the change. undo() pops that entry and restores it. This handles multiple updates to the same node correctly—each undo peels back one layer.
Return True when an undo succeeds, False when the stack is empty.
Tree Traversal
Build the children map during initialization by iterating through all nodes and grouping by parent. Then use iterative DFS to sum the subtree:
- Use an explicit stack (not recursion) to avoid stack overflow on deep trees
- For each visited node, add its value to the total and call the cache-access logic
- Push all children onto the stack
Complexity Analysis
| Operation | Time | Space |
|---|---|---|
__init__ | O(N) | O(N) for store + children map |
get | O(1) | O(k) for cache |
update | O(1) | O(1) per operation |
undo | O(1) | O(U) total for U updates |
get_subtree_sum | O(S) | O(S) for traversal stack |
The cache uses O(k) space. Undo history accumulates, using O(U) space for U updates. If memory is a concern, consider a bounded undo buffer that discards old entries.
Edge Cases
- Small capacity: With
k=1, every access evicts the previous entry - Large subtrees: If the subtree has more nodes than cache capacity, early nodes get evicted—this is expected behavior
- Multiple roots: Nodes with
parent=Noneor parents not in the dataset are treated as separate roots - Deep chains: Iterative DFS handles arbitrarily deep trees without stack overflow
- Empty undo: Returns
Falsewithout error
Code
class _DLLNode:
__slots__ = ('id', 'value', 'prev', 'next')
def __init__(self, id=None, value=None):
self.id = id
self.value = value
self.prev = self.next = None
class TreeSystem:
def __init__(self, nodes, capacity):
if capacity < 1:
raise ValueError("Capacity must be at least 1")
# Authoritative store
self._store = {nid: val for nid, (val, _) in nodes.items()}
# Build children map for downward traversal
self._children = {}
for nid in nodes:
self._children[nid] = []
for nid, (_, parent) in nodes.items():
if parent is not None and parent in self._children:
self._children[parent].append(nid)
# LRU cache: map + doubly-linked list with sentinels
self._capacity = capacity
self._cache_map = {}
self._head = _DLLNode() # sentinel
self._tail = _DLLNode() # sentinel
self._head.next = self._tail
self._tail.prev = self._head
# Undo stack
self._undo_stack = []
def _remove_from_list(self, node):
"""Unlink a node from the doubly-linked list"""
node.prev.next = node.next
node.next.prev = node.prev
def _add_to_front(self, node):
"""Insert a node right after the head (most recent position)"""
node.prev = self._head
node.next = self._head.next
self._head.next.prev = node
self._head.next = node
def _mark_accessed(self, node_id, value):
"""Record an access: cache the node and mark as most recently used"""
if node_id in self._cache_map:
# Already cached: refresh value and move to front
node = self._cache_map[node_id]
node.value = value
self._remove_from_list(node)
self._add_to_front(node)
else:
# New entry: create node and cache
node = _DLLNode(node_id, value)
self._cache_map[node_id] = node
self._add_to_front(node)
# Evict if over capacity
if len(self._cache_map) > self._capacity:
lru = self._tail.prev
self._remove_from_list(lru)
del self._cache_map[lru.id]
def _sync_cache_if_present(self, node_id, value):
"""Write-through: update cached copy if present (doesn't affect recency)"""
if node_id in self._cache_map:
self._cache_map[node_id].value = value
def get(self, node_id):
if node_id not in self._store:
raise KeyError(f"Node {node_id} not found")
value = self._store[node_id]
self._mark_accessed(node_id, value)
return value
def update(self, node_id, new_value):
if node_id not in self._store:
raise KeyError(f"Node {node_id} not found")
old_value = self._store[node_id]
self._undo_stack.append((node_id, old_value))
self._store[node_id] = new_value
self._sync_cache_if_present(node_id, new_value)
def undo(self):
if not self._undo_stack:
return False
node_id, old_value = self._undo_stack.pop()
self._store[node_id] = old_value
self._sync_cache_if_present(node_id, old_value)
return True
def get_subtree_sum(self, root_id):
if root_id not in self._store:
raise KeyError(f"Node {root_id} not found")
total = 0
stack = [root_id]
while stack:
current = stack.pop()
value = self._store[current]
total += value
self._mark_accessed(current, value)
# Add children to stack
stack.extend(self._children.get(current, []))
return total
Common Mistakes
- Forgetting to synchronize: Updating the store but not the cache leads to stale reads
- Updating recency on writes: The problem states traversal caches nodes, but writes typically shouldn't affect LRU order
- Recursive DFS: Can overflow on deep trees; use an explicit stack instead
- Not handling empty undo: Should be a safe no-op, not an error
- Building children map inefficiently: Iterating nodes once is O(N); searching for children each time is O(N²)