Implement Cache, Undo, and DFS
NetflixSoftware Engineer · OnsiteLast updated
This problem tests your ability to combine a Least Recently Used (LRU) cache with a command-based undo system, applied to a hierarchical tree structure traversal.
Problem Statement
You are building a metadata management system for a hierarchical organizational structure represented as a tree, where each node has a unique id and a value. Implement a system that supports three main operations: caching access to nodes, modifying values with undo capability, and performing a depth-first search (DFS) to retrieve a total aggregate value.
Requirements
- LRU Cache: Maintain a cache of the most recently accessed nodes with a fixed capacity
k. If the cache is full, evict the least recently used node. - Command Undo: Support an
update(id, new_value)operation. Each update must be stored in a stack. Anundo()operation should revert the most recent update to its previous state. - DFS Traversal: Implement a
get_subtree_sum(root_id)function that returns the sum of values of the subtree rooted atroot_id. This traversal must also cache each node's value as it visits it.
Interface
class OrgSystem:
def __init__(self, nodes, capacity):
# nodes is a dict: {id: (value, parent_id)}
pass
def get(self, id):
# Returns value, updates cache, uses LRU eviction
pass
def update(self, id, new_value):
# Updates value, pushes change to undo stack
pass
def undo(self):
# Reverts the last update
pass
def get_subtree_sum(self, root_id):
# Performs DFS, returns sum of subtree values
pass
Constraints
- Number of nodes
N <= 10^5. - Cache capacity
kis between1andN. - Ensure
undooperations are thread-safe or logically sound.
Example
Input: nodes = {1: (10, None), 2: (5, 1), 3: (3, 1)}, capacity = 2
get(2) -> returns 5
update(2, 20) -> value of 2 becomes 20
undo() -> value of 2 reverts to 5
Hints
Hint 1
Use a Doubly Linked List combined with a Hash Map to implement the O(1) LRU cache.
Hint 2
The undo stack should store tuples containing the node ID and its previous value to allow for simple reversal.
Hint 3
For the DFS traversal, use an adjacency list constructed from the parent pointers to easily navigate children.
Follow-up questions
- How would you modify the cache to handle concurrent access in a multi-threaded environment?
- What is the time complexity of the undo operation if you have to perform it N times consecutively?
- If the tree structure itself could be modified (e.g., re-parenting nodes), how would that impact your DFS implementation and cache invalidation?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.