Design a Tree-Based Storage Simulator with Auto-Renaming
Data Structure DesignModel answerLast updated
Build an in-memory file store that auto-creates parent folders, renames clashing files with the lowest free numeric tag, and lists folder contents in ASCII order.
Task
Build a small in-memory storage system shaped like a file tree. When a file is stored, any folders along its path that do not yet exist must be created automatically. If a file with the requested name is already present in the target folder, the system must pick a new name by inserting a numeric tag, using the smallest tag that gives an unused name.
Implement the class FileVault:
FileVault()creates a vault that contains only the root folder/.add_file(path: str) -> strstores a file at the absolute pathpath, creating missing parent folders. It returns the absolute path under which the file was actually stored, after any renaming.list_dir(path: str) -> list[str]returns the names of all direct children (subfolders and files) of the folder atpath, sorted in ASCII order. Ifpathdoes not exist, or points to a file, return an empty list. Listing must never create anything.
Renaming rules
Split a file name into a base and an extension:
- If the name contains a
.at an index greater than 0, take the last such.. The extension is everything from that dot to the end, and the base is everything before it. For example,"archive.tar.gz"gives base"archive.tar"and extension".gz". - If there is no
., or the only.is at index 0 (such as".env"), the extension is empty and the base is the whole name. - If the name is already used in the target folder, try
base + " (" + k + ")" + extfork = 1, 2, 3, ...and use the first name not already in the folder.
Interface
class FileVault:
def __init__(self):
pass
def add_file(self, path: str) -> str:
pass
def list_dir(self, path: str) -> list[str]:
pass
Constraints
- Every path is absolute and starts with
/. - Paths are ASCII, contain no
//, and have no trailing slash (except the root/itself). - Names never contain
/. - At most 10,000 calls in total to
add_fileandlist_dir. - Within one folder, a file and a subfolder never have the same name.
Examples
v = FileVault()
v.add_file("/docs/report.pdf") # "/docs/report.pdf"
v.add_file("/docs/report.pdf") # "/docs/report (1).pdf"
v.add_file("/docs/report.pdf") # "/docs/report (2).pdf"
v.list_dir("/docs")
# ["report (1).pdf", "report (2).pdf", "report.pdf"]
v = FileVault()
v.add_file("/home/.bashrc") # "/home/.bashrc"
v.add_file("/home/.bashrc") # "/home/.bashrc (1)"
v.add_file("/home/notes (2).txt") # "/home/notes (2).txt"
v.add_file("/home/notes.txt") # "/home/notes.txt"
v.add_file("/home/notes.txt") # "/home/notes (1).txt"
v.list_dir("/home")
# [".bashrc", ".bashrc (1)", "notes (1).txt", "notes (2).txt", "notes.txt"]
What to deliver
Describe your data model, explain how you pick the new name and why it yields the smallest valid tag, give the code, and state its time and space complexity. Mention the edge cases you would test.
Hints
Hint 1
Represent each folder as a node holding a map of child folders and a set of file names. Creating parents is then the same walk as `mkdir -p`.
Hint 2
A single counter per base name is not enough: a user can add `notes (2).txt` explicitly, and the next `notes.txt` clash must still get `(1)`. Probe the real set of names instead.
Hint 3
Pay attention to splitting the path `/` (it must give no components), to dotfiles whose only dot is at index 0, and to `list_dir` not creating nodes while it walks.
Hint 4
For the follow-up on huge numbers of duplicates, remember per folder and per (base, extension) the next tag worth trying, so each tag is skipped at most once.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the vault as a tree of folder nodes. Each node stores:
dirs: a dict mapping child folder name to child nodefiles: a set of file names in that folder
Two independent concerns make up the solution: walking the tree, and choosing a free name.
Walking the tree
add_file splits the path on / and discards empty pieces, so "/" becomes [] and "/a/b.txt" becomes ["a", "b.txt"]. Every component except the last is a folder. Starting at the root, look each one up in dirs and create it if absent. This guarantees all ancestors exist when we reach the last folder.
list_dir walks the same way but never creates anything. If any component is missing from dirs, return []. Files are never stored in dirs, so a path that ends at a file also fails the final lookup and returns [] with no special case.
Choosing the name
- Use
rfind('.'). If the index is greater than 0, split intobase = name[:i]andext = name[i:]. Otherwisebase = nameandext = "". - If the requested name is free, use it as is.
- Otherwise try
f"{base} ({k}){ext}"fork = 1, 2, ...and take the first free one.
"Free" means the name is in neither files nor dirs. The constraints say a file and folder never share a name, so checking both keeps that guarantee even if a generated name happens to equal a folder name.
Why the tag is the smallest
We test k in increasing order against the actual contents of the folder and stop at the first unused name. The result is therefore the minimum by construction. This is why a plain per-name counter fails: after notes (2).txt is added explicitly, a counter would hand out (1) only by luck and could later collide or skip. Probing the real set handles every history correctly. Explicitly added names such as notes (2).txt are treated as ordinary names and never parsed back into base and counter.
Code
class _Dir:
__slots__ = ("dirs", "files")
def __init__(self):
self.dirs = {}
self.files = set()
def has(self, name):
return name in self.files or name in self.dirs
class FileVault:
def __init__(self):
self.root = _Dir()
@staticmethod
def _parts(path):
return [p for p in path.split("/") if p]
@staticmethod
def _split_name(name):
i = name.rfind(".")
if i > 0:
return name[:i], name[i:]
return name, ""
def add_file(self, path):
*parents, name = self._parts(path)
node = self.root
for p in parents:
nxt = node.dirs.get(p)
if nxt is None:
nxt = _Dir()
node.dirs[p] = nxt
node = nxt
final = name
if node.has(final):
base, ext = self._split_name(name)
k = 1
while node.has(f"{base} ({k}){ext}"):
k += 1
final = f"{base} ({k}){ext}"
node.files.add(final)
return "/" + "/".join(parents + [final])
def list_dir(self, path):
node = self.root
for p in self._parts(path):
node = node.dirs.get(p)
if node is None:
return []
return sorted(list(node.dirs) + list(node.files))
Ordering
Python compares strings by code point, which for ASCII is exactly the required order. Space (32) is smaller than . (46), so "notes (1).txt" comes before "notes.txt", matching the examples.
Complexity
Let L be the path length and c the number of children of the listed folder.
add_file: O(L) for the walk, plus up tokprobes, each a hash lookup on a newly built string of length about|name|.list_dir: O(L + c log c) because of the sort.- Space: O(total characters of all stored names), since each name lives in exactly one node.
With at most 10,000 operations, even the worst case of thousands of probes per insert (a few tens of millions of cheap lookups) is acceptable.
Edge cases to test
- Listing
/, and adding a file directly under/. - Dotfiles:
.envbecomes.env (1). - Several dots:
a.tar.gzbecomesa.tar (1).gz. - A trailing dot:
file.has basefileand extension., givingfile (1).. - Gaps: with
x.txtandx (2).txtpresent, the nextx.txtgivesx (1).txt, and the one after givesx (3).txt. list_diron a missing path or a file returns[]and leaves the tree unchanged.
Common mistakes
- Treating a leading dot as an extension separator.
- Using one counter per name, which breaks when suffixed names are added explicitly.
- Creating nodes during
list_dir(for example by usingsetdefaultwhile walking). - Producing
[""]when splitting"/". - Sorting by something other than raw string order, such as case-insensitive order.
Follow-ups
Very many duplicates of one name. Store per folder a map from (base, ext) to a pointer next_k, the smallest tag that might be free. Start probing there and set the pointer to the chosen tag plus one. Without deletions, every tag below the pointer is occupied, so each tag is skipped at most once and inserts are amortized O(1). If deletions are allowed, keep a min-heap of freed tags per key and consult it first, discarding stale entries lazily.
Moving a folder. Because nodes know only their children by name, a move is detaching the node from one parent and attaching it to another, costing O(depth) regardless of subtree size. Reject moves into the folder's own subtree by walking up from the destination (using parent pointers) and checking whether the source is encountered. Apply the same renaming rule at the destination if the name is taken.