Build a Bounded In-Memory File System with Auto-Rename
Data Structure DesignModel answerLast updated
Design a trie-backed file system supporting path-based file insertion and directory listing, with a per-directory capacity cap and OS-style duplicate renaming.
Bounded In-Memory File System
Build a class that simulates a hierarchical file system entirely in memory. You need to support two operations.
Operations
add_file(path: str) -> str
path is an absolute-style string such as "projects/backend/main.py". A leading / is optional and should be treated equivalently. The method must:
- Create any intermediate directories that do not already exist.
- Store a file node at the final component.
- Return the actual path under which the file was stored (which may differ from the input if a rename occurred — see below).
list_dir(path: str) -> list[str]
Given a directory path (e.g. "projects/backend" or "" for the root), return the names of its immediate children in insertion order. A child may be a file or a subdirectory; return the name only, not the full path.
Constraints
1. Per-directory capacity limit
Each directory may hold at most 5 entries (files and subdirectories combined). If inserting a file would require adding a sixth entry to any directory along the path, reject the entire operation and leave the file system unchanged. This means no intermediate directories created during the call should persist either.
2. Automatic rename on collision
Within a single directory, every entry must have a unique name. If the requested leaf filename is already taken (by a file or a folder with the same name), do not reject the call — instead rename the new file using this scheme:
- Split the name at its last
.to getbaseand.ext. A name with no dot, or whose only dot is at the start (e.g..gitignore), is treated as having no extension. - Append a numeric suffix to the base:
base(1).ext,base(2).ext, and so on, picking the lowest integer that produces a free name. - Maintain a per-directory counter per requested name so you do not scan from 1 on every call.
- Do not parse existing suffixes. Treat the incoming name as an opaque base. For example, if
report(1).pdfalready exists and a secondreport(1).pdfis added, the new file becomesreport(1)(1).pdf.
Example sequence (all files land in the same directory):
add_file("docs/report.pdf") → "docs/report.pdf"
add_file("docs/report.pdf") → "docs/report(1).pdf"
add_file("docs/report(1).pdf") → "docs/report(1)(1).pdf"
What to address
- Clarify any ambiguous behaviors before writing code (invalid paths, conflicts between files and directories, idempotency, case sensitivity).
- Implement both methods with correct handling of every constraint.
- Analyze time and space complexity.
- Call out the edge cases your implementation handles explicitly.
Hints
Hint 1
Model the file system as a trie where each node stores a dictionary of children. What extra per-node state do you need to enforce the capacity limit and to generate rename suffixes efficiently without scanning from 1 every time?
Hint 2
The capacity check only ever matters at one directory per call. Think about which directory that is — newly created directories start empty, so they can never be the one that overflows. Identify that single choke-point and check it before making any mutation to keep the operation atomic.
Hint 3
Extension splitting and suffix generation are their own mini-problems. Decide upfront: where is the extension boundary for names like `a.tar.gz` or `.bashrc`? And when must you increment past the stored counter — hint: a user could have added `report(1).pdf` manually before any collision occurred.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the file system as a trie of nodes. Each directory node holds:
children: dict[str, Node]— maps entry name to child node, preserving insertion order (Python 3.7+ dicts).counters: dict[str, int]— maps a requested filename to the next suffix integer to try. This avoids re-scanning from 1 on every duplicate.
Files are leaf nodes with no children dict.
Clarifying the contract
Before writing a line of code, pin these down:
| Question | Decision |
|---|---|
Leading / | Strip it; "/a/b.txt" and "a/b.txt" are the same path. |
| Root listing | list_dir("") or list_dir("/") lists the root. |
| Empty/dot components | "a//b", "a/./b" are invalid — raise an error. |
| Intermediate node is a file | Reject with NotADirectoryError. |
| Capacity check timing | Check before any mutation so a rejected call changes nothing. |
| Rename idempotency | add_file is deliberately not idempotent: repeating a call creates a renamed copy, it does not deduplicate. |
| Suffix parsing | Do not parse incoming names. report(1).pdf is an opaque name whose duplicates become report(1)(1).pdf. |
| Extension boundary | Last dot wins: a.tar.gz → base a.tar, ext .gz. Names with no dot or a leading dot only (.gitignore) have no extension. |
| Case sensitivity | Case-sensitive (Linux-style). |
Return value of add_file | The final stored path, so callers learn about any rename. |
The atomic capacity insight
When add_file walks the directory tree, it finds the deepest existing directory D and then creates new subdirectories below it. Every newly created directory starts empty, so none of them can overflow. D is the only existing directory that gains a new child. One pre-mutation check — len(D.children) < 5 — makes the whole operation atomic. If it fails, nothing has been written yet.
Renaming also consumes a slot. A rename in an already-full directory must still be rejected.
Rename logic
def _assign_name(directory, requested):
if requested not in directory.children:
return requested
base, ext = split_ext(requested) # split at last dot
k = directory.counters.get(requested, 1)
while f"{base}({k}){ext}" in directory.children:
k += 1
directory.counters[requested] = k + 1
return f"{base}({k}){ext}"
The while loop is necessary because a user may have manually inserted report(1).pdf before any collision, causing the stored counter to point to an already-occupied name.
Complexity
Let L = total characters in the path, C = capacity (5).
add_file: O(L) time. Each path component costs one hash lookup proportional to its length. The rename loop runs at mostC + 1times (a directory holds ≤ C entries), each iteration building a name of length O(len(leaf)).list_dir: O(L + C) time — O(L) to walk the path, O(C) to collect children names.- Space: O(S) where S = total characters across all stored names. Counter maps are bounded by the number of children per directory.
Common mistakes
- Partial mutation on rejection. Creating subdirectories before checking capacity, then failing mid-way, leaves the tree dirty. Fix: identify which directory needs the new entry before touching anything.
- Scanning from 1 every time. Without counters, the rename loop is O(C²) in the worst case and semantically wrong when manually named files occupy slots.
- Wrong extension split. Using
os.path.splitextorstr.split(".", 1)gives the wrong result fora.tar.gz. Userfind(".")and check the dot is not the first character. - Forgetting that rename still adds an entry. The capacity guard must run even when a rename is in progress.
Python implementation
from __future__ import annotations
class CapacityError(Exception):
"""A directory would exceed its entry limit."""
class InvalidPathError(ValueError):
"""The path string is malformed."""
class _Node:
__slots__ = ("is_dir", "children", "counters")
def __init__(self, is_dir: bool) -> None:
self.is_dir = is_dir
self.children: dict[str, _Node] | None = {} if is_dir else None
self.counters: dict[str, int] | None = {} if is_dir else None
def _split_path(path: str, require_leaf: bool) -> list[str]:
"""Normalise path to a list of components."""
p = path.lstrip("/").rstrip("/") if not require_leaf else path.lstrip("/")
parts = p.split("/") if p else []
if any(c in ("", ".", "..") for c in parts):
raise InvalidPathError(f"invalid path: {path!r}")
if require_leaf and not parts:
raise InvalidPathError("path must include a filename")
return parts
def _split_ext(name: str) -> tuple[str, str]:
"""Split at the last dot, ignoring a leading dot."""
dot = name.rfind(".")
if dot <= 0: # no dot, or dot is the very first char
return name, ""
return name[:dot], name[dot:]
class FileSystem:
def __init__(self, max_entries: int = 5) -> None:
self._cap = max_entries
self._root = _Node(is_dir=True)
# ------------------------------------------------------------------ #
# Internal helpers #
# ------------------------------------------------------------------ #
def _walk_dirs(self, dir_parts: list[str]) -> tuple[_Node, int]:
"""Return (deepest existing dir node, index of first missing part)."""
node = self._root
for i, part in enumerate(dir_parts):
child = node.children.get(part)
if child is None:
return node, i
if not child.is_dir:
raise NotADirectoryError(
f"'{'/'.join(dir_parts[:i+1])}' is a file, not a directory"
)
node = child
return node, len(dir_parts)
def _assign_name(self, directory: _Node, requested: str) -> str:
"""Return a free name in *directory*, renaming if necessary."""
if requested not in directory.children:
return requested
base, ext = _split_ext(requested)
k = directory.counters.get(requested, 1)
while f"{base}({k}){ext}" in directory.children:
k += 1
directory.counters[requested] = k + 1
return f"{base}({k}){ext}"
# ------------------------------------------------------------------ #
# Public API #
# ------------------------------------------------------------------ #
def add_file(self, path: str) -> str:
parts = _split_path(path, require_leaf=True)
dir_parts, leaf = parts[:-1], parts[-1]
# Walk to the deepest existing directory.
pivot, first_new = self._walk_dirs(dir_parts)
# `pivot` is the only existing directory gaining a new child.
# Check capacity before touching anything (atomicity).
if len(pivot.children) >= self._cap:
raise CapacityError(
f"directory at depth {first_new} is full "
f"(max {self._cap} entries)"
)
# Determine the actual leaf name (may be renamed).
# Renaming only applies when the leaf directory already existed.
leaf_dir_exists = (first_new == len(dir_parts))
if leaf_dir_exists:
final_leaf = self._assign_name(pivot if not dir_parts else
self._resolve_dir(dir_parts),
leaf)
else:
final_leaf = leaf # brand-new directory, no collision possible
# Now build new intermediate directories and the file node.
node = pivot
for part in dir_parts[first_new:]:
new_dir = _Node(is_dir=True)
node.children[part] = new_dir
node = new_dir
# node is now the immediate parent of the leaf.
if leaf_dir_exists:
# We resolved the name above against the existing leaf directory.
pass
else:
# Recalculate: node is fresh and empty, no rename needed.
final_leaf = leaf
node.children[final_leaf] = _Node(is_dir=False)
stored_path = "/".join(dir_parts + [final_leaf])
return stored_path
def _resolve_dir(self, dir_parts: list[str]) -> _Node:
"""Walk all parts, assuming they all exist."""
node = self._root
for part in dir_parts:
node = node.children[part]
return node
def list_dir(self, path: str) -> list[str]:
parts = _split_path(path, require_leaf=False)
node = self._root
for i, part in enumerate(parts):
child = node.children.get(part)
if child is None:
raise FileNotFoundError(f"no such directory: {path!r}")
if not child.is_dir:
raise NotADirectoryError(f"'{path}' is a file")
node = child
return list(node.children.keys())
Edge cases explicitly handled
add_file("a/b.txt/c.txt")whereb.txtis a file →NotADirectoryError.- A sixth entry in any existing directory →
CapacityError; no intermediate dirs are created. - Leaf directory is fresh → no rename can occur (empty directory).
docsexists as a folder anddocsis added as a file → stored asdocs(1)(no extension).list_diron a file path →NotADirectoryError; on a missing path →FileNotFoundError.File.txtandfile.txtare distinct (case-sensitive).