call(back)
Algorithms & Data StructuresmediumSign in to star problems

Files and Folders Workspace

Build an in-memory workspace of files and folders. Every resource has a generated id ("r1", "r2", ... in creation order, never reused), a name, a type ("FILE" or "FOLDER") and a parent folder; null as a parent means the home level.

  • createResource(name, type, parentId): returns the new id, or null when the parent does not exist or is a file. Names need not be unique.
  • listResources(folderId): the ids of the folder's direct children in insertion order (null for the home level), or null when the folder does not exist or is a file.
  • deleteResource(id): deletes the resource and, for a folder, everything under it; returns whether the id existed.
  • moveResource(id, newParentId): moves the resource to the end of the new parent's children; returns false when either id is unknown, the target is a file, or the target is the resource itself or anything under it.
ws = new Workspace()
ws.createResource("docs", "FOLDER", null)     ->  "r1"
ws.createResource("a.txt", "FILE", "r1")     ->  "r2"
ws.createResource("b.txt", "FILE", "r2")     ->  null    // a file cannot be a parent
ws.listResources("r1")                       ->  ["r2"]
ws.moveResource("r1", "r1")                  ->  false   // into itself
ws.deleteResource("r1")                      ->  true    // takes r2 with it
ws.listResources(null)                       ->  []

Up to 100,000 resources and operations.

Hints

Hint 1

Keep two structures that answer different questions: a map from id to its record with a parent pointer for walking up, and a list of child ids per folder for listing in order.

Hint 2

The subtree check on a move is a walk up from the target through parent pointers looking for the moved id: O(depth), not a traversal of the moved subtree.

Hint 3

On delete, remove the id from its parent's list too, and drop the deleted folder's own children entry, or a later list or move sees a ghost.

Topics

Asked at

Similar Problems6