Immutable Folder Tree State with Safe Move and Delete
Data Structure DesignModel answerLast updated
Design a normalized, immutable state model for a nested folder tree and implement add, move (with cycle rejection) and recursive delete efficiently for deep trees.
Folder Tree State Manager
You are writing the logic layer behind a file-explorer widget that shows folders nested to any depth. The UI needs a state model plus three update functions. Every folder has a unique id, a name, a parentId (empty for top-level folders), and a list of child folders.
What to build
- State model. Choose a representation that lets you find any folder by its ID in O(1) or O(log n) time.
- Operations, each returning the new state:
add_folder(state, parent_id, name): create a new folder under the given parent (or at the top level if the parent isNone).move_folder(state, folder_id, new_parent_id): re-parent a folder. The move must be rejected if it would put a folder inside itself or inside one of its own descendants.delete_folder(state, folder_id): remove the folder together with everything beneath it.
Suggested interface
# state = {
# 'folders': { id: {'id': ..., 'name': ..., 'parentId': ..., 'children': [...]} },
# 'rootIds': [...]
# }
def add_folder(state, parent_id, name): ...
def move_folder(state, folder_id, new_parent_id): ...
def delete_folder(state, folder_id): ...
Constraints
- Tree depth is not bounded.
- Up to 10,000 operations may be applied.
- Do not deep-clone the whole state on each operation. Use a normalized layout and/or immutable updates that share untouched parts.
Example
Folder C is a child of folder B. Calling move_folder(state, 'B', 'C') must be rejected because a cycle would be created.
Edge cases to handle
- Moving a folder to the parent it already has.
- Deleting a top-level folder.
- A folder being renamed while a drag-and-move of it is in progress.
In your answer, explain the data model, the algorithm for each operation, why the structure stays valid, the complexity, and how you deal with the edge cases.
Hints
Hint 1
Store folders in a flat map keyed by ID, and let each folder hold the IDs of its children instead of nested objects. Then updating one folder never touches its subtree.
Hint 2
Keep a parentId pointer on every folder. To check whether a move is legal, walk upward from the proposed new parent; if you meet the folder being moved, the target is inside its subtree.
Hint 3
Recursion will break on very deep trees, so use an explicit stack for subtree deletion. Also remember to unlink the deleted folder from its parent's child list (or from the root list).
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
1. Normalize the state
A nested structure (children holding full objects) makes every operation costly: finding a node needs a search, updating a node means rebuilding every ancestor, and cycle checks need a subtree scan. Instead use a flat, normalized layout:
state = {
'folders': { id: {'id', 'name', 'parentId', 'children': [childId, ...]} },
'rootIds': [id, ...]
}
foldersis a dict, so lookup by ID is O(1).- Children are stored as IDs, so changing a folder never requires copying its descendants.
parentIdis a back-pointer, which makes upward walks cheap. The cycle check relies on it.rootIdslists top-level folders. The structure is a forest, so there can be several roots or none.
2. Immutable updates with structural sharing
Each operation returns a new state object. Only what changes is copied: the outer folders dict (a shallow copy of pointers), the affected folder records, and the affected children or rootIds lists. All other records are shared by reference between old and new states. This makes undo/redo simple and lets a UI detect change with an identity check.
3. Operations
add_folder
- Validate that the parent exists (if given) and the ID is not a duplicate.
- Create a leaf record and add its ID to the parent's
children(orrootIds), copying only that parent record and list.
move_folder
- Look up the folder; raise on unknown IDs.
- If
new_parent_idequals the currentparentId, return the same state object (no-op). - Cycle check: starting at
new_parent_id, followparentIdupward. If you reachfolder_id, the target is the folder itself or a descendant, so reject the move. Cost is O(depth) and it never walks the moved subtree. - Otherwise remove the ID from the old parent's list (or
rootIds), add it to the new parent's list (orrootIdsifnew_parent_idisNone), and update the folder'sparentId.
delete_folder
- Collect the subtree with an iterative DFS (explicit stack) and remove each ID from the copied
foldersdict. - Remove the deleted folder's ID from its parent's
childrenor fromrootIds.
4. Why it is correct
Invariants:
f.parentId = pexactly whenf.idappears once infolders[p].children.parentId is Noneexactly whenf.idappears once inrootIds.- The parent graph has no cycles.
add creates a leaf and links both directions. move relinks both directions, and a cycle can only form if the new parent lies in the moved folder's subtree. Every node in that subtree has folder_id on its ancestor chain, so the upward walk catches exactly the forbidden case. The walk terminates because the existing graph is acyclic. delete removes a complete subtree and the single outside reference to it, so no dangling IDs remain.
5. Code
import uuid
class CycleError(ValueError):
pass
def create_state():
return {'folders': {}, 'rootIds': []}
def _get(state, fid):
try:
return state['folders'][fid]
except KeyError:
raise KeyError(f"Unknown folder: {fid}") from None
def _detach(folders, root_ids, fid, parent_id):
if parent_id is None:
return [r for r in root_ids if r != fid]
p = folders[parent_id]
folders[parent_id] = {**p, 'children': [c for c in p['children'] if c != fid]}
return root_ids
def _attach(folders, root_ids, fid, parent_id):
if parent_id is None:
return root_ids + [fid]
p = folders[parent_id]
folders[parent_id] = {**p, 'children': p['children'] + [fid]}
return root_ids
def add_folder(state, parent_id, name, folder_id=None):
if parent_id is not None:
_get(state, parent_id)
fid = folder_id or uuid.uuid4().hex
if fid in state['folders']:
raise ValueError("Duplicate id")
folders = dict(state['folders'])
folders[fid] = {'id': fid, 'name': name, 'parentId': parent_id, 'children': []}
roots = _attach(folders, state['rootIds'], fid, parent_id)
return {'folders': folders, 'rootIds': roots}
def move_folder(state, folder_id, new_parent_id):
f = _get(state, folder_id)
if new_parent_id is not None:
_get(state, new_parent_id)
if f['parentId'] == new_parent_id:
return state
cur = new_parent_id
while cur is not None:
if cur == folder_id:
raise CycleError("Cannot move a folder into its own subtree")
cur = state['folders'][cur]['parentId']
folders = dict(state['folders'])
roots = _detach(folders, state['rootIds'], folder_id, f['parentId'])
roots = _attach(folders, roots, folder_id, new_parent_id)
folders[folder_id] = {**f, 'parentId': new_parent_id}
return {'folders': folders, 'rootIds': roots}
def delete_folder(state, folder_id):
f = _get(state, folder_id)
folders = dict(state['folders'])
stack = [folder_id]
while stack:
cur = stack.pop()
stack.extend(folders.pop(cur)['children'])
roots = _detach(folders, state['rootIds'], folder_id, f['parentId'])
return {'folders': folders, 'rootIds': roots}
Note: in delete_folder, _detach must be called after the subtree is popped, and it only touches the parent, which is never part of the deleted subtree.
6. Complexity
Let n be the folder count, d the depth, s the sibling count and k the deleted subtree size.
| Operation | Time |
|---|---|
| lookup | O(1) |
| add | O(s) plus shallow dict copy |
| move | O(d + s) plus shallow dict copy |
| delete | O(k + s) plus shallow dict copy |
The shallow dict copy is O(n) pointer copies, not a deep clone. For 10,000 operations on typical trees this is fine. If it becomes a bottleneck, use a persistent hash map (HAMT), which makes each update O(log n).
7. Edge cases
- Move to the current parent: return the same state object so subscribers see no change.
- Move into itself: the walk starts at
folder_id, so it is caught as a cycle. - Move to top level:
new_parent_id=Noneappends torootIds. - Delete a top-level folder: remove it from
rootIds; deleting the last one leaves a valid empty forest. - Unknown IDs: raise
KeyErrorrather than corrupting state. - Rename during a drag: everything references folders by ID, never by name or object. A rename is just another immutable update to one record. The drag holds only
folder_id, and the drop applies to the latest state, so the moved folder keeps its new name. - Very deep trees: the ancestor walk and the delete DFS are iterative, avoiding Python's recursion limit.
Common mistakes
- Keeping nested child objects, which forces ancestor rebuilds and slow lookups.
- Checking for cycles by scanning the moved subtree instead of walking the new parent's ancestors.
- Using recursion for delete or traversal on unbounded depth.
- Forgetting to update both the old and new parent lists, or leaving the deleted ID in its parent's
children. - Deep-cloning the state on every operation.