KatInterview

Immutable Folder Tree State with Safe Move and Delete

Data Structure DesignModel answer
EasyModel answerData Structure Designtreestate-managementimmutability

Last 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

  1. State model. Choose a representation that lets you find any folder by its ID in O(1) or O(log n) time.
  2. 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 is None).
    • 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).