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_id must take O(1) average time.
  • Every function must treat state as strictly immutable: never mutate the input state or 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_id appears in state["folders"][p]["children"] if and only if state["folders"][child_id]["parentId"] == p, and parentId is None if and only if the folder's ID appears in state["rootIds"].

Required Operations

Implement the following four functions matching starter.py:

  1. add_folder(state, parent_id, name, folder_id=None)
    • Creates a new folder with "children": [] under parent_id (when parent_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 of state["rootIds"] when parent_id is None).
    • Generates a unique ID automatically when folder_id is None.
    • Raises KeyError if parent_id is not None and not present in state["folders"]; raises ValueError if folder_id already exists in state["folders"].
  2. move_folder(state, folder_id, new_parent_id)
    • Relocates folder_id (and its entire subtree) to the end of new_parent_id's children list, or to the end of state["rootIds"] when new_parent_id is None.
    • If folder_id's current parentId already equals new_parent_id, returns the input state unchanged without altering sibling order.
    • Raises KeyError if folder_id is unknown or if new_parent_id is not None and unknown.
    • Raises ValueError if new_parent_id is folder_id itself or any descendant of folder_id (cycle prevention).
  3. delete_folder(state, folder_id)
    • Removes folder_id and every descendant folder in its subtree from state["folders"], and removes folder_id from its parent's children list (or from state["rootIds"] if top-level).
    • Raises KeyError if folder_id is unknown.
  4. rename_folder(state, folder_id, new_name)
    • Returns a new state updating only state["folders"][folder_id]["name"] to new_name.
    • Raises KeyError if folder_id is unknown.

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"] == [] and s4["folders"]["p9"]["children"] == ["p2"]
  • s5["folders"]["p2"]["name"] == "LegacyAPI" and s5["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 (leaving state unmodified).
  • Call 2 returns state unchanged (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,000 sequential 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-None hashable value, including falsy values such as 0 or "".
  • Untouched folder dictionaries and extra top-level keys on state must be preserved by reference across updates.

Step-by-step walkthrough

  1. 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 display name, a parentId (None at top level), and an ordered children list of child IDs. Each operation (add_folder, move_folder, delete_folder, and rename_folder) receives state and 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. Passing parent_id=None targets the top level.
    • Explicit vs auto-generated IDs: add_folder generates a fresh ID via uuid.uuid4().hex only when folder_id is None. Checking is None (never if not folder_id) ensures falsy IDs such as 0 or "" work just like strings.
    • Validation before copying: Unknown IDs raise KeyError; duplicate IDs in add_folder or cycle-creating moves raise ValueError without touching state.
    • Same-parent move short-circuit: Calling move_folder(state, "f20", "f10") when "f20" already sits under "f10" returns state unchanged 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_folder and move_folder modify disjoint fields and commute cleanly.
  2. 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 to O(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 in O(1) average time.
    • children gives ordered downward links for rendering; parentId gives direct O(1) upward access to the parent.
    • Bidirectional invariant: child_id is in folders[p]["children"] if and only if folders[child_id]["parentId"] == p (and parentId is None if and only if folder_id is in rootIds).
  3. 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 in O(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_state
    

    Starting _new_state with dict(state) preserves any extra keys stored alongside "folders" and "rootIds" (such as "ui": {"selectedId": "p2"}).

  4. Implement add_folder

    add_folder executes in three clear phases: 1. Validate: If parent_id is not None, verify the parent exists via _get. Generate a UUID when folder_id is None, then reject duplicate IDs with ValueError. 2. Insert record: Shallow-copy state["folders"] and insert the new record with "children": []. 3. Link upward and downward: Append folder_id to a new rootIds list (when parent_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)
    
  5. Detect cycles in move_folder by climbing parentId pointers

    Re-parenting folder_id under new_parent_id creates a cycle (a detached loop where a folder becomes an ancestor of itself) whenever new_parent_id equals folder_id or lies anywhere inside folder_id's descendants.

    Compare the two ways of testing that condition: - Slow downward scan: Visit every descendant of folder_id, costing O(subtree_size) even when folder_id owns thousands of subfolders. - Fast upward climb: Start at new_parent_id and follow parentId links straight up toward None. Every node has only one chain of ancestors, taking O(depth) steps! Checking current == top_id on 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 while loop 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 False
    
  6. Implement 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_id from old_parent_id's children (or from rootIds if top-level). 2. Append folder_id to new_parent_id's children (or to rootIds if moving to top level). 3. Shallow-copy folder_id's record with "parentId": new_parent_id. Because folder_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)
    
  7. Implement delete_folder iteratively and rename_folder

    In a normalized store, deleting "p9" by only calling del folders["p9"] would leave "p9"'s child "p2" stranded inside folders as an unreachable orphan! We must collect "p9" and every descendant ID in its subtree, remove all of them from folders, and unlink "p9" from its parent (or rootIds).

    Because tree depth can exceed Python's 1,000-frame recursion limit, _subtree_ids uses 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_folder shallow-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"])
    
  8. 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.
    
  9. 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, because state["folders"] is a hash map indexed directly by folder_id.
  • add_folder time: O(n) overall (O(c) to copy the parent's children list of length c, plus O(n) pointer copies for the shallow dict(state["folders"]) copy).
  • move_folder time: O(1) when re-parenting onto the current parent (immediate return), and O(n) overall otherwise (O(d) to climb at most d + 1 ancestors from new_parent_id, O(c) to copy the old and new parents' children lists, and O(n) for the shallow folders map copy).
  • delete_folder time: O(n) overall (O(s) to pop all s doomed subtree IDs from the explicit stack and delete their keys, O(c) to filter folder_id out of its parent's children list, and O(n) for the shallow folders map copy).
  • rename_folder time: O(n) overall (O(1) record copy plus the O(n) shallow folders map copy).
  • Space: O(n) per returned state for the shallow-copied folders dictionary of n references (plus O(s) temporary stack memory during delete_folder), while all n - 3 or more untouched folder records are shared in O(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) tests current == top_id on iteration 1 (catching move_folder(s, "f20", "f20")) and climbs all the way to None (catching arbitrarily deep descendants).
  • Top-level moves and root deletions (parentId is None): Moving to None skips the ancestor walk and appends to rootIds; deleting a root removes its ID from rootIds cleanly, including when deleting the last remaining folder.
  • Deep hierarchies (3,000+ levels): Both _is_in_subtree and _subtree_ids use iterative while loops rather than recursion, avoiding Python's 1,000-frame RecursionError.
  • Falsy folder IDs (0 or ""): Testing parent_id is None rather than truthiness (if not parent_id) ensures 0 and "" behave identically to ordinary string IDs.
  • Concurrent rename during an active drag-and-drop: Carrying only folder_id in drag state ensures rename_folder and move_folder update independent fields and produce the same final state in either order.

Common mistakes

  • Mutating state or folder["children"] in place (.append() / .remove()): Corrupts historical snapshots (breaking undo/redo) and causes memoized UI rows comparing prevProps.folder === nextProps.folder to miss updates.
  • Calling copy.deepcopy(state) on every operation: Clones all n folder 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 in state["folders"] as unreachable orphans.
  • Updating parentId without updating children (or rootIds): Breaks the bidirectional invariant so top-down and bottom-up traversals disagree.
  • Writing if parent_id: instead of if parent_id is not None:: Misclassifies folder ID 0 as top-level None.
  • Recursing during subtree deletion: Triggers RecursionError on deep chains.

Alternative approaches

  • Nested folder objects ({"id": "p1", "children": [...]}): Simple for static display, but random ID lookup degrades to O(n) and immutable updates must clone every ancestor up to the root.
  • Parent-pointer-only records (no children lists): Avoids dual-link updates, but listing a folder's children requires scanning all n records (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 for O(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 in O(1) time. Always key rows by stable folder.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_id and repeatedly joins children via the (parent_id, position) index in O(subtree_size * log N) time. For read-dominated workloads, pair it with a closure table folder_ancestors(ancestor_id, descendant_id, depth) storing every ancestor-descendant pair so subtree fetches become a single indexed lookup on ancestor_id (trading O(subtree_size * depth) row updates during move_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) and focusedId in UI state alongside folders, following the WAI-ARIA tree / treeitem specification with a roving tabindex (tabIndex=0 on focusedId, tabIndex=-1 elsewhere). Derive a flat visibleIds array via depth-first traversal from rootIds that descends only into folders present in expandedIds. Then ArrowDown and ArrowUp step focusedId to visibleIds[idx + 1] and visibleIds[idx - 1]; ArrowRight expands a collapsed folder (or moves focus to its first child when already expanded); ArrowLeft collapses an expanded folder (or jumps straight to folders[focusedId]["parentId"] in O(1) time when already collapsed); and Home / End jump to visibleIds[0] and visibleIds[-1].

Follow-up questions

Similar questions

More UiPath interview questions

All 13 UiPath questions →