Immutable State Engine for a Folder Tree
Easy · Software Engineering Fundamentals · Frontend Engineer · Onsite
Problem Statement
Design and implement an immutable, normalized state management module in pure Python for a hierarchical UI directory tree.
State Representation
The store dictionary has two primary keys (and may also hold arbitrary extra UI metadata keys that must survive updates untouched):
state = {
"folders": {
folder_id: {
"id": folder_id,
"name": str,
"parentId": parent_id_or_None,
"children": [child_folder_ids],
},
},
"rootIds": [top_level_folder_ids],
}
- Looking up any folder record by
folder_idmust takeO(1)average time. - Every function must treat
stateas strictly immutable: never mutate the inputstateor any nested dictionary/list inside it. Instead, return a new state dictionary that reuses unmodified folder records by object reference (structural sharing) rather than deep-copying the entire tree. - Bidirectional link invariant:
child_idappears instate["folders"][p]["children"]if and only ifstate["folders"][child_id]["parentId"] == p, andparentId is Noneif and only if the folder's ID appears instate["rootIds"].
Required Operations
Implement the following four functions matching starter.py:
add_folder(state, parent_id, name, folder_id=None)- Creates a new folder with
"children": []underparent_id(whenparent_id is None, adds a top-level folder). - Appends the new folder ID to the end of
state["folders"][parent_id]["children"](or to the end ofstate["rootIds"]whenparent_id is None). - Generates a unique ID automatically when
folder_id is None. - Raises
KeyErrorifparent_idis notNoneand not present instate["folders"]; raisesValueErroriffolder_idalready exists instate["folders"].
- Creates a new folder with
move_folder(state, folder_id, new_parent_id)- Relocates
folder_id(and its entire subtree) to the end ofnew_parent_id'schildrenlist, or to the end ofstate["rootIds"]whennew_parent_id is None. - If
folder_id's currentparentIdalready equalsnew_parent_id, returns the inputstateunchanged without altering sibling order. - Raises
KeyErroriffolder_idis unknown or ifnew_parent_idis notNoneand unknown. - Raises
ValueErrorifnew_parent_idisfolder_iditself or any descendant offolder_id(cycle prevention).
- Relocates
delete_folder(state, folder_id)- Removes
folder_idand every descendant folder in its subtree fromstate["folders"], and removesfolder_idfrom its parent'schildrenlist (or fromstate["rootIds"]if top-level). - Raises
KeyErroriffolder_idis unknown.
- Removes
rename_folder(state, folder_id, new_name)- Returns a new state updating only
state["folders"][folder_id]["name"]tonew_name. - Raises
KeyErroriffolder_idis unknown.
- Returns a new state updating only
Examples
Example 1
Input:
s0 = {"folders": {}, "rootIds": []}
s1 = add_folder(s0, None, "Projects", "p1")
s2 = add_folder(s1, "p1", "Backend", "p2")
s3 = add_folder(s2, None, "Archive", "p9")
s4 = move_folder(s3, "p2", "p9")
s5 = rename_folder(s4, "p2", "LegacyAPI")
s6 = delete_folder(s5, "p9")
Output:
s4["folders"]["p1"]["children"] == []ands4["folders"]["p9"]["children"] == ["p2"]s5["folders"]["p2"]["name"] == "LegacyAPI"ands5["folders"]["p1"] is s4["folders"]["p1"]s6 == {"folders": {"p1": {"id": "p1", "name": "Projects", "parentId": None, "children": []}}, "rootIds": ["p1"]}
Walk-through: "p1" and "p9" start at top level with "p2" nested inside "p1". Moving "p2" to "p9" detaches "p2" from "p1" and appends it to "p9". Renaming "p2" clones only "p2"'s dictionary so "p1" keeps the exact same object identity. Deleting "p9" purges both "p9" and its child "p2", leaving only "p1".
Example 2
Input:
# Chain: f10 ("Eng", root) -> f20 ("Platform") -> f30 ("Auth")
move_folder(state, "f20", "f30") # Call 1
move_folder(state, "f20", "f10") # Call 2
Output:
- Call 1 raises
ValueError(leavingstateunmodified). - Call 2 returns
stateunchanged (move_folder(state, "f20", "f10") is state).
Walk-through: Walking upward from prospective parent "f30" reaches "f20", proving "f30" lies inside "f20"'s subtree—re-parenting "f20" under "f30" would detach a loop from the root, so Call 1 raises ValueError. In Call 2, "f20" already has parentId == "f10", so the function short-circuits and returns state directly.
Constraints
- Up to
10,000sequential state operations. - Hierarchy depth is unbounded (chains of
3,000+nested folders must succeed without hitting Python's recursion limit). - Folder IDs may be any non-
Nonehashable value, including falsy values such as0or"". - Untouched folder dictionaries and extra top-level keys on
statemust be preserved by reference across updates.
Step-by-step walkthrough
Restate the problem and pin down edge-case rules
We are implementing the pure-Python state reducer behind a nested UI folder view. Every folder record stores a unique
id, a displayname, aparentId(Noneat top level), and an orderedchildrenlist of child IDs. Each operation (add_folder,move_folder,delete_folder, andrename_folder) receivesstateand returns a new state dictionary without mutating the input.Pin down the exact behavior on tricky inputs before writing code:
- Ordered top-level roots:
state["rootIds"]lists top-level folder IDs in insertion/move order. Passingparent_id=Nonetargets the top level. - Explicit vs auto-generated IDs:
add_foldergenerates a fresh ID viauuid.uuid4().hexonly whenfolder_id is None. Checkingis None(neverif not folder_id) ensures falsy IDs such as0or""work just like strings. - Validation before copying: Unknown IDs raise
KeyError; duplicate IDs inadd_folderor cycle-creating moves raiseValueErrorwithout touchingstate. - Same-parent move short-circuit: Calling
move_folder(state, "f20", "f10")when"f20"already sits under"f10"returnsstateunchanged instead of shifting"f20"to the end of"f10"'s children. - Concurrent rename and drag: Because links store immutable IDs rather than display names,
rename_folderandmove_foldermodify disjoint fields and commute cleanly.
- Ordered top-level roots:
Why normalize the hierarchy into an ID-indexed map
A common beginner instinct is to nest child dictionaries directly inside parent dictionaries:
Nested tree (O(n) scan to locate an arbitrary ID): {"id": "p1", "name": "Projects", "children": [ {"id": "p2", "name": "Backend", "children": [ {"id": "p3", "name": "Auth", "children": []} ]} ]}In a nested representation, finding
"p3"by ID requires walking up toO(n)nodes, and updating"p3"immutably forces cloning every ancestor along the chain from"p1"to"p3".Instead, UI state containers use normalized state — keeping every folder record in a single top-level map indexed by folder ID, with upward and downward ID pointers:
Normalized state (O(1) average lookup by ID): state = { "folders": { "p1": {"id": "p1", "name": "Projects", "parentId": None, "children": ["p2"]}, "p2": {"id": "p2", "name": "Backend", "parentId": "p1", "children": ["p3"]}, "p3": {"id": "p3", "name": "Auth", "parentId": "p2", "children": []}, }, "rootIds": ["p1"], }state["folders"][folder_id]resolves any folder inO(1)average time.childrengives ordered downward links for rendering;parentIdgives directO(1)upward access to the parent.- Bidirectional invariant:
child_idis infolders[p]["children"]if and only iffolders[child_id]["parentId"] == p(andparentId is Noneif and only iffolder_idis inrootIds).
Immutable updates with structural sharing
Avoiding
copy.deepcopy(state)relies on structural sharing: shallow-copy only the outer dictionaries and the 1–3 folder records that actually changed, while reusing the exact same dictionary objects in memory for every untouched folder.Rename "p2" from "Backend" to "LegacyAPI": old state["folders"] new state["folders"] (new dict) "p1" -----------------------------> {"id": "p1", ...} (reused: old is new!) "p9" -----------------------------> {"id": "p9", ...} (reused: old is new!) "p2" ---> {"name": "Backend", ...} "p2" ---> {"name": "LegacyAPI", ...} (new copy)Because untouched records retain object identity (
s5["folders"]["p1"] is s4["folders"]["p1"]), memoized UI components can skip re-rendering untouched rows inO(1)time. Five small helpers handle these shallow updates cleanly:from typing import Any, Dict, List, Optional import uuid def _get(state: Dict[str, Any], folder_id: Any) -> Dict[str, Any]: """Return the folder record for folder_id, or raise KeyError if missing.""" folders = state["folders"] if folder_id not in folders: raise KeyError("unknown folder id: " + repr(folder_id)) return folders[folder_id] def _remove_id(ids: List[Any], target_id: Any) -> List[Any]: """Return a new list preserving order with target_id filtered out.""" remaining: List[Any] = [] for item_id in ids: if item_id != target_id: remaining.append(item_id) return remaining def _with_child(folder: Dict[str, Any], child_id: Any) -> Dict[str, Any]: """Return a shallow-copied folder record with child_id appended to children.""" updated_folder = dict(folder) updated_folder["children"] = folder["children"] + [child_id] return updated_folder def _without_child(folder: Dict[str, Any], child_id: Any) -> Dict[str, Any]: """Return a shallow-copied folder record with child_id removed from children.""" updated_folder = dict(folder) updated_folder["children"] = _remove_id(folder["children"], child_id) return updated_folder def _new_state( state: Dict[str, Any], folders: Dict[Any, Dict[str, Any]], root_ids: List[Any], ) -> Dict[str, Any]: """Build a new top-level state dict while preserving unrelated keys (e.g., UI state).""" next_state = dict(state) next_state["folders"] = folders next_state["rootIds"] = root_ids return next_stateStarting
_new_statewithdict(state)preserves any extra keys stored alongside"folders"and"rootIds"(such as"ui": {"selectedId": "p2"}).Implement add_folder
add_folderexecutes in three clear phases: 1. Validate: Ifparent_id is not None, verify the parent exists via_get. Generate a UUID whenfolder_id is None, then reject duplicate IDs withValueError. 2. Insert record: Shallow-copystate["folders"]and insert the new record with"children": []. 3. Link upward and downward: Appendfolder_idto a newrootIdslist (whenparent_id is None) or to a shallow-copied parent record via_with_child.def add_folder( state: Dict[str, Any], parent_id: Optional[Any], name: str, folder_id: Optional[Any] = None, ) -> Dict[str, Any]: # Phase 1: Validate parent existence and pick/validate the new folder ID. # Use `is not None` / `is None` so falsy IDs like 0 or "" are not treated as None. if parent_id is not None: _get(state, parent_id) if folder_id is None: folder_id = uuid.uuid4().hex if folder_id in state["folders"]: raise ValueError("folder id already exists: " + repr(folder_id)) # Phase 2: Shallow-copy the folders index so untouched folder records are shared. folders = dict(state["folders"]) folders[folder_id] = { "id": folder_id, "name": name, "parentId": parent_id, "children": [], } # Phase 3: Link the new folder into rootIds (top-level) or its parent's children list. root_ids = state["rootIds"] if parent_id is None: root_ids = root_ids + [folder_id] else: folders[parent_id] = _with_child(folders[parent_id], folder_id) return _new_state(state, folders, root_ids)Detect cycles in move_folder by climbing parentId pointers
Re-parenting
folder_idundernew_parent_idcreates a cycle (a detached loop where a folder becomes an ancestor of itself) whenevernew_parent_idequalsfolder_idor lies anywhere insidefolder_id's descendants.Compare the two ways of testing that condition: - Slow downward scan: Visit every descendant of
folder_id, costingO(subtree_size)even whenfolder_idowns thousands of subfolders. - Fast upward climb: Start atnew_parent_idand followparentIdlinks straight up towardNone. Every node has only one chain of ancestors, takingO(depth)steps! Checkingcurrent == top_idon iteration 1 also catches self-moves (move_folder(state, "f20", "f20")) automatically:Chain (Example 2): f10 -> f20 -> f30 Attempt: move_folder(state, folder_id="f20", new_parent_id="f30") Climb UP from candidate_id="f30" checking against top_id="f20": current = "f30" (== "f20"? No) -> step to parentId "f20" current = "f20" (== "f20"? YES!) -> Cycle detected! Raise ValueError.Using a
whileloop rather than recursion handles arbitrarily deep folder chains safely:def _is_in_subtree(folders: Dict[Any, Dict[str, Any]], candidate_id: Any, top_id: Any) -> bool: """Return True if candidate_id equals top_id or lies inside top_id's subtree.""" # Walk UP parentId pointers in O(depth) instead of scanning top_id's whole subtree. # Checking current == top_id on iteration 1 also catches moving top_id into itself. current = candidate_id while current is not None: if current == top_id: return True current = folders[current]["parentId"] return FalseImplement move_folder
Once endpoint checks, the same-parent short-circuit, and the cycle check pass, moving a folder modifies at most three folder records: 1. Remove
folder_idfromold_parent_id'schildren(or fromrootIdsif top-level). 2. Appendfolder_idtonew_parent_id'schildren(or torootIdsif moving to top level). 3. Shallow-copyfolder_id's record with"parentId": new_parent_id. Becausefolder_id["children"]still lists its child IDs, its entire subtree moves automatically without touching a single descendant!def move_folder( state: Dict[str, Any], folder_id: Any, new_parent_id: Optional[Any], ) -> Dict[str, Any]: # Phase 1: Validate that both endpoints exist before touching any state. folder = _get(state, folder_id) if new_parent_id is not None: _get(state, new_parent_id) # Phase 2: Short-circuit no-op moves so sibling order and object identity stay intact. old_parent_id = folder["parentId"] if old_parent_id == new_parent_id: return state # Phase 3: Reject moves into folder_id itself or any of its descendants (cycle check). if new_parent_id is not None and _is_in_subtree(state["folders"], new_parent_id, folder_id): raise ValueError("cycle detected: cannot move a folder into itself or its descendant") # Phase 4: Detach from the old parent (or rootIds) and attach to the new parent (or rootIds). folders = dict(state["folders"]) root_ids = state["rootIds"] if old_parent_id is None: root_ids = _remove_id(root_ids, folder_id) else: folders[old_parent_id] = _without_child(folders[old_parent_id], folder_id) if new_parent_id is None: root_ids = root_ids + [folder_id] else: folders[new_parent_id] = _with_child(folders[new_parent_id], folder_id) # Phase 5: Copy only the moved folder record to update parentId; descendants move automatically. moved_folder = dict(folder) moved_folder["parentId"] = new_parent_id folders[folder_id] = moved_folder return _new_state(state, folders, root_ids)Implement delete_folder iteratively and rename_folder
In a normalized store, deleting
"p9"by only callingdel folders["p9"]would leave"p9"'s child"p2"stranded insidefoldersas an unreachable orphan! We must collect"p9"and every descendant ID in its subtree, remove all of them fromfolders, and unlink"p9"from its parent (orrootIds).Because tree depth can exceed Python's 1,000-frame recursion limit,
_subtree_idsuses an explicit stack (a plain list driving an iterative depth-first loop):def _subtree_ids(folders: Dict[Any, Dict[str, Any]], top_id: Any) -> List[Any]: """Collect top_id and every descendant ID using an explicit stack.""" # Iterative traversal avoids RecursionError when folder depth exceeds 1,000. collected: List[Any] = [] # stack holds folder IDs discovered so far whose children still need to be visited. stack: List[Any] = [top_id] while stack: current_id = stack.pop() collected.append(current_id) for child_id in folders[current_id]["children"]: stack.append(child_id) return collected def delete_folder(state: Dict[str, Any], folder_id: Any) -> Dict[str, Any]: """Remove folder_id and its whole subtree. KeyError: unknown id.""" # Phase 1: Look up target and gather every ID in its subtree so no orphans leak. folder = _get(state, folder_id) folders = dict(state["folders"]) for doomed_id in _subtree_ids(state["folders"], folder_id): del folders[doomed_id] # Phase 2: Unlink folder_id from its parent's children list or from rootIds. parent_id = folder["parentId"] root_ids = state["rootIds"] if parent_id is None: root_ids = _remove_id(root_ids, folder_id) else: folders[parent_id] = _without_child(folders[parent_id], folder_id) return _new_state(state, folders, root_ids)rename_foldershallow-copies just the target record with its updated"name":def rename_folder(state: Dict[str, Any], folder_id: Any, new_name: str) -> Dict[str, Any]: """Change only the name of folder_id. KeyError: unknown id.""" # Copy only the target folder record; parent, children, and rootIds stay untouched. folder = _get(state, folder_id) folders = dict(state["folders"]) renamed_folder = dict(folder) renamed_folder["name"] = new_name folders[folder_id] = renamed_folder return _new_state(state, folders, state["rootIds"])Walk through Example 1 step by step
Trace the full sequence from Example 1:
After s3 (Projects -> Backend, plus Archive): rootIds = ["p1", "p9"] p1: name="Projects", parentId=None, children=["p2"] p2: name="Backend", parentId="p1", children=[] p9: name="Archive", parentId=None, children=[] s4 = move_folder(s3, "p2", "p9"): -> Climb from "p9": "p9" -> None (no cycle). -> p1.children = [], p9.children = ["p2"], p2.parentId = "p9". s5 = rename_folder(s4, "p2", "LegacyAPI"): -> Only p2 is copied (name="LegacyAPI"); s5["folders"]["p1"] is s4["folders"]["p1"]. s6 = delete_folder(s5, "p9"): -> _subtree_ids pops "p9", pushes/pops "p2" -> deletes both "p9" and "p2". -> rootIds becomes ["p1"]; only "p1" remains in folders.Complete solution
from typing import Any, Dict, List, Optional import uuid # Normalized state shape: # state = { # "folders": { # "p1": {"id": "p1", "name": "Projects", "parentId": None, "children": ["p2"]}, # "p2": {"id": "p2", "name": "Backend", "parentId": "p1", "children": []}, # }, # "rootIds": ["p1"], # ordered IDs of top-level folders (parentId is None) # } # Invariant: child_id is in folders[p]["children"] if and only if folders[child_id]["parentId"] == p. def _get(state: Dict[str, Any], folder_id: Any) -> Dict[str, Any]: """Return the folder record for folder_id, or raise KeyError if missing.""" folders = state["folders"] if folder_id not in folders: raise KeyError("unknown folder id: " + repr(folder_id)) return folders[folder_id] def _remove_id(ids: List[Any], target_id: Any) -> List[Any]: """Return a new list preserving order with target_id filtered out.""" remaining: List[Any] = [] for item_id in ids: if item_id != target_id: remaining.append(item_id) return remaining def _with_child(folder: Dict[str, Any], child_id: Any) -> Dict[str, Any]: """Return a shallow-copied folder record with child_id appended to children.""" updated_folder = dict(folder) updated_folder["children"] = folder["children"] + [child_id] return updated_folder def _without_child(folder: Dict[str, Any], child_id: Any) -> Dict[str, Any]: """Return a shallow-copied folder record with child_id removed from children.""" updated_folder = dict(folder) updated_folder["children"] = _remove_id(folder["children"], child_id) return updated_folder def _new_state( state: Dict[str, Any], folders: Dict[Any, Dict[str, Any]], root_ids: List[Any], ) -> Dict[str, Any]: """Build a new top-level state dict while preserving unrelated keys (e.g., UI state).""" next_state = dict(state) next_state["folders"] = folders next_state["rootIds"] = root_ids return next_state def _is_in_subtree(folders: Dict[Any, Dict[str, Any]], candidate_id: Any, top_id: Any) -> bool: """Return True if candidate_id equals top_id or lies inside top_id's subtree.""" # Walk UP parentId pointers in O(depth) instead of scanning top_id's whole subtree. # Checking current == top_id on iteration 1 also catches moving top_id into itself. current = candidate_id while current is not None: if current == top_id: return True current = folders[current]["parentId"] return False def _subtree_ids(folders: Dict[Any, Dict[str, Any]], top_id: Any) -> List[Any]: """Collect top_id and every descendant ID using an explicit stack.""" # Iterative traversal avoids RecursionError when folder depth exceeds 1,000. collected: List[Any] = [] # stack holds folder IDs discovered so far whose children still need to be visited. stack: List[Any] = [top_id] while stack: current_id = stack.pop() collected.append(current_id) for child_id in folders[current_id]["children"]: stack.append(child_id) return collected def add_folder( state: Dict[str, Any], parent_id: Optional[Any], name: str, folder_id: Optional[Any] = None, ) -> Dict[str, Any]: """Add a folder under parent_id (None: a new top-level folder). The new folder goes at the end of its parent's children (or of rootIds). If folder_id is None a fresh id is generated. KeyError: unknown parent_id. ValueError: folder_id already exists. """ # Phase 1: Validate parent existence and pick/validate the new folder ID. # Use `is not None` / `is None` so falsy IDs like 0 or "" are not treated as None. if parent_id is not None: _get(state, parent_id) if folder_id is None: folder_id = uuid.uuid4().hex if folder_id in state["folders"]: raise ValueError("folder id already exists: " + repr(folder_id)) # Phase 2: Shallow-copy the folders index so untouched folder records are shared. folders = dict(state["folders"]) folders[folder_id] = { "id": folder_id, "name": name, "parentId": parent_id, "children": [], } # Phase 3: Link the new folder into rootIds (top-level) or its parent's children list. root_ids = state["rootIds"] if parent_id is None: root_ids = root_ids + [folder_id] else: folders[parent_id] = _with_child(folders[parent_id], folder_id) return _new_state(state, folders, root_ids) def move_folder( state: Dict[str, Any], folder_id: Any, new_parent_id: Optional[Any], ) -> Dict[str, Any]: """Move folder_id (with its subtree) to the end of new_parent_id's children. new_parent_id None makes it a top-level folder. Moving to the current parent returns the input state unchanged. KeyError: unknown id. ValueError: new_parent_id is the folder or its descendant. """ # Phase 1: Validate that both endpoints exist before touching any state. folder = _get(state, folder_id) if new_parent_id is not None: _get(state, new_parent_id) # Phase 2: Short-circuit no-op moves so sibling order and object identity stay intact. old_parent_id = folder["parentId"] if old_parent_id == new_parent_id: return state # Phase 3: Reject moves into folder_id itself or any of its descendants (cycle check). if new_parent_id is not None and _is_in_subtree(state["folders"], new_parent_id, folder_id): raise ValueError("cycle detected: cannot move a folder into itself or its descendant") # Phase 4: Detach from the old parent (or rootIds) and attach to the new parent (or rootIds). folders = dict(state["folders"]) root_ids = state["rootIds"] if old_parent_id is None: root_ids = _remove_id(root_ids, folder_id) else: folders[old_parent_id] = _without_child(folders[old_parent_id], folder_id) if new_parent_id is None: root_ids = root_ids + [folder_id] else: folders[new_parent_id] = _with_child(folders[new_parent_id], folder_id) # Phase 5: Copy only the moved folder record to update parentId; descendants move automatically. moved_folder = dict(folder) moved_folder["parentId"] = new_parent_id folders[folder_id] = moved_folder return _new_state(state, folders, root_ids) def delete_folder(state: Dict[str, Any], folder_id: Any) -> Dict[str, Any]: """Remove folder_id and its whole subtree. KeyError: unknown id.""" # Phase 1: Look up target and gather every ID in its subtree so no orphans leak. folder = _get(state, folder_id) folders = dict(state["folders"]) for doomed_id in _subtree_ids(state["folders"], folder_id): del folders[doomed_id] # Phase 2: Unlink folder_id from its parent's children list or from rootIds. parent_id = folder["parentId"] root_ids = state["rootIds"] if parent_id is None: root_ids = _remove_id(root_ids, folder_id) else: folders[parent_id] = _without_child(folders[parent_id], folder_id) return _new_state(state, folders, root_ids) def rename_folder(state: Dict[str, Any], folder_id: Any, new_name: str) -> Dict[str, Any]: """Change only the name of folder_id. KeyError: unknown id.""" # Copy only the target folder record; parent, children, and rootIds stay untouched. folder = _get(state, folder_id) folders = dict(state["folders"]) renamed_folder = dict(folder) renamed_folder["name"] = new_name folders[folder_id] = renamed_folder return _new_state(state, folders, state["rootIds"])✅ Submit now — all tests should pass.
Intuition & how it works
Think of an organization chart stored in an employee badge directory rather than inside nested physical binders. Every folder gets one flat index card in state["folders"][id] recording its name, its parent's ID (parentId), and an ordered list of its immediate subfolder IDs (children), while state["rootIds"] lists top-level IDs. This flat layout is called normalized state: every item lives in a single top-level map indexed by ID, and hierarchy links are stored as ID references instead of deeply nested objects.
A naive implementation nests folder dictionaries directly inside one another ({"id": "p1", "children": [{"id": "p2", ...}]}) and calls deepcopy on every update. That breaks down at scale: finding a folder by ID scans up to all n nodes instead of performing one hash lookup, and deep-cloning allocates brand-new objects for every folder, forcing a UI library to re-render the entire screen on a tiny edit. Pairing normalized state with structural sharing (copying only the outer map and the 1–3 folder cards that changed, while reusing untouched cards by reference) makes ID lookups instant and leaves untouched UI rows undisturbed.
Walk through our two examples step by step:
1. Cycle prevention (move_folder(state, "f20", "f30") on f10 -> f20 -> f30): Starting at candidate parent "f30", we climb parentId links ("f30" -> "f20"). Hitting "f20" proves "f30" is inside "f20"'s subtree—moving "f20" under "f30" would form a cycle (a detached loop where "f20" becomes its own ancestor), so we raise ValueError.
2. Valid move & rename (p1 -> p2 plus p9): Moving "p2" to "p9" climbs from "p9" to None safely, then replaces only three cards ("p1", "p9", "p2"). Renaming "p2" to "LegacyAPI" copies only "p2", so "p1" keeps its exact object identity (s5["folders"]["p1"] is s4["folders"]["p1"]).
3. Subtree delete (delete_folder(s5, "p9")): Using an explicit stack (a plain Python list driving an iterative depth-first loop), we pop "p9", push/pop "p2", delete both cards from folders, and filter "p9" out of rootIds.
Complexity
Let n be the total number of folders in state["folders"], d the ancestor depth of new_parent_id, c the length of a modified children list (or rootIds), and s the size of a deleted subtree (with d, c, s <= n).
- Lookup by ID:
O(1)average time, becausestate["folders"]is a hash map indexed directly byfolder_id. add_foldertime:O(n)overall (O(c)to copy the parent'schildrenlist of lengthc, plusO(n)pointer copies for the shallowdict(state["folders"])copy).move_foldertime:O(1)when re-parenting onto the current parent (immediate return), andO(n)overall otherwise (O(d)to climb at mostd + 1ancestors fromnew_parent_id,O(c)to copy the old and new parents'childrenlists, andO(n)for the shallowfoldersmap copy).delete_foldertime:O(n)overall (O(s)to pop allsdoomed subtree IDs from the explicit stack and delete their keys,O(c)to filterfolder_idout of its parent'schildrenlist, andO(n)for the shallowfoldersmap copy).rename_foldertime:O(n)overall (O(1)record copy plus theO(n)shallowfoldersmap copy).- Space:
O(n)per returned state for the shallow-copiedfoldersdictionary ofnreferences (plusO(s)temporary stack memory duringdelete_folder), while alln - 3or more untouched folder records are shared inO(1)space with the prior state.
In CPython, shallow-copying a 10,000-entry dict copies raw C pointers in roughly 30 microseconds (~0.3 seconds across 10,000 operations). For much larger stores, replacing dict with a persistent hash-array mapped trie (HAMT) (such as immutables.Map, which shares internal trie nodes across versions) reduces the O(n) map copy to O(log n).
Edge cases
- Re-parenting onto the current parent: Checked before any copying (
if old_parent_id == new_parent_id: return state), preserving both sibling order and object identity. - Self-move or deep-descendant move:
_is_in_subtree(folders, new_parent_id, folder_id)testscurrent == top_idon iteration 1 (catchingmove_folder(s, "f20", "f20")) and climbs all the way toNone(catching arbitrarily deep descendants). - Top-level moves and root deletions (
parentId is None): Moving toNoneskips the ancestor walk and appends torootIds; deleting a root removes its ID fromrootIdscleanly, including when deleting the last remaining folder. - Deep hierarchies (
3,000+levels): Both_is_in_subtreeand_subtree_idsuse iterativewhileloops rather than recursion, avoiding Python's 1,000-frameRecursionError. - Falsy folder IDs (
0or""): Testingparent_id is Nonerather than truthiness (if not parent_id) ensures0and""behave identically to ordinary string IDs. - Concurrent rename during an active drag-and-drop: Carrying only
folder_idin drag state ensuresrename_folderandmove_folderupdate independent fields and produce the same final state in either order.
Common mistakes
- Mutating
stateorfolder["children"]in place (.append()/.remove()): Corrupts historical snapshots (breaking undo/redo) and causes memoized UI rows comparingprevProps.folder === nextProps.folderto miss updates. - Calling
copy.deepcopy(state)on every operation: Clones allnfolder records instead of 1–3, wasting CPU/memory and destroying structural sharing so every UI row re-renders. - Checking only immediate children for cycles (
new_parent["parentId"] == folder_id): Misses moving"f10"under its grandchild"f30", severing a closed loop from the root. - Deleting
folders[folder_id]without purging its descendants: Leaves all nested subfolders stranded instate["folders"]as unreachable orphans. - Updating
parentIdwithout updatingchildren(orrootIds): Breaks the bidirectional invariant so top-down and bottom-up traversals disagree. - Writing
if parent_id:instead ofif parent_id is not None:: Misclassifies folder ID0as top-levelNone. - Recursing during subtree deletion: Triggers
RecursionErroron deep chains.
Alternative approaches
- Nested folder objects (
{"id": "p1", "children": [...]}): Simple for static display, but random ID lookup degrades toO(n)and immutable updates must clone every ancestor up to the root. - Parent-pointer-only records (no
childrenlists): Avoids dual-link updates, but listing a folder's children requires scanning allnrecords (or maintaining a secondary child index anyway) plus an explicit sort-order field. - Mutable store with targeted pub/sub events: Mutate records in place and emit fine-grained events (
folderMoved,folderRenamed) with affected IDs, trading away free undo/redo snapshots and reference-equality checks forO(1)outer container cost.
Follow-up questions
- How can a frontend view layer prevent full-tree UI re-renders when a state update modifies only a single folder? Wrap each tree row in a memoized component (such as
React.memo, which skips re-rendering whenever its props keep identical object references) subscribed by ID (state.folders[folderId]). Because structural sharing allocates new dictionaries only for the 1–3 affected folders (for example, old parent, new parent, and moved folder), every other folder row receives the exact same object reference and bails out inO(1)time. Always key rows by stablefolder.id(never list index), and when thousands of folders are expanded simultaneously, flatten visible expanded nodes into a single virtualized list that mounts only the ~30 rows intersecting the scroll viewport. - When storing this hierarchy in SQL, which table design lets you query an arbitrary folder's descendants without scanning the whole table? Use an adjacency list table
folders(id PRIMARY KEY, parent_id REFERENCES folders(id) NULL, name, position)backed by a B-tree index on(parent_id, position), and query any subtree with a recursive CTE (Common Table Expression) that seeds:root_idand repeatedly joins children via the(parent_id, position)index inO(subtree_size * log N)time. For read-dominated workloads, pair it with a closure tablefolder_ancestors(ancestor_id, descendant_id, depth)storing every ancestor-descendant pair so subtree fetches become a single indexed lookup onancestor_id(tradingO(subtree_size * depth)row updates duringmove_folder), or maintain an indexed materialized path string ('/p1/p2/p3/') queried by prefix (LIKE '/p1/p2/%'). - How would you design arrow-key focus movement and expand/collapse shortcuts across the visible folder hierarchy? Track
expandedIds(the set of open folder IDs) andfocusedIdin UI state alongsidefolders, following the WAI-ARIAtree/treeitemspecification with a rovingtabindex(tabIndex=0onfocusedId,tabIndex=-1elsewhere). Derive a flatvisibleIdsarray via depth-first traversal fromrootIdsthat descends only into folders present inexpandedIds. ThenArrowDownandArrowUpstepfocusedIdtovisibleIds[idx + 1]andvisibleIds[idx - 1];ArrowRightexpands a collapsed folder (or moves focus to its first child when already expanded);ArrowLeftcollapses an expanded folder (or jumps straight tofolders[focusedId]["parentId"]inO(1)time when already collapsed); andHome/Endjump tovisibleIds[0]andvisibleIds[-1].
Follow-up questions
- How can a frontend view layer prevent full-tree UI re-renders when a state update modifies only a single folder?
- When storing this hierarchy in SQL, which table design lets you query an arbitrary folder's descendants without scanning the whole table?
- How would you design arrow-key focus movement and expand/collapse shortcuts across the visible folder hierarchy?
Similar questions
- Longest Repeat-Free Substring Ignoring Case
- Shortest Knight-Style Jumps on an Unbounded Grid
- End-to-End Project Walkthrough and Engineering Ownership
- Core ML Optimization, Regularization, and Encoding
- Storage Architecture and Query Consistency Guarantees
- Transformer Block Internals, Math, and Feed-Forward Role
More UiPath interview questions
- Decoder Transformers, Beam Search, and Low-Rank Adaptation Medium
- Stopping-Score Cap Probability Under Uniform Draws Medium
- Engineering Dependable LLM Tool Use: Structured Outputs, Recovery, and Loop Control Medium Pro
- Shortest Knight-Style Jumps on an Unbounded Grid Medium Pro
- Longest Repeat-Free Substring Ignoring Case Medium Pro
- End-to-End Project Walkthrough and Engineering Ownership Medium Pro
- Core ML Optimization, Regularization, and Encoding Easy Pro
- Transformer Block Internals, Math, and Feed-Forward Role Medium Pro
- Storage Architecture and Query Consistency Guarantees Hard Pro
- Bidirectional Bubble Sort with Adaptive Bounds Medium Pro