KatInterview

Build a Tree System with LRU Cache and Command History

Data Structure DesignModel answer
MediumModel answerData Structure Designlru-cachetree-traversalcommand-pattern

Last 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:

  1. 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.

  2. 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.

  3. 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