Strict In-Memory Directory Tree and Shell Command Interpreter
Hard · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
Build an in-memory hierarchical file system rooted at "/" and expose a batch interpreter execute_commands that processes a list of shell-style command strings sequentially:
def execute_commands(commands: List[str]) -> List[object]:
Starting from an empty root directory "/", evaluate each string in commands in order and return a list of results of matching length. When a command fails, record {"error": "<message>"} at that index without halting subsequent commands.
Evaluation Order & Error Precedence
Validate every command in the exact sequence below and return the first matching error:
- Command verb & arity: Split the string on whitespace (
command.split(), ignoring leading/trailing whitespace and collapsing consecutive spaces).- Supported verbs (case-sensitive):
"mkdir","touch","ls","rm","rmdir". - Empty input or an unrecognized verb ->
{"error": "unknown command"}. - Token count other than
2->{"error": "wrong number of arguments"}.
- Supported verbs (case-sensitive):
- Strict path syntax: Let
pathbe the second token.pathmust equal"/"or start with"/"followed by one or more non-empty component names separated by single"/"characters (trailing slashes like"/logs/"and repeated slashes like"//logs"are invalid).- Every component name may contain only ASCII letters (
A-Z,a-z), digits (0-9),.,_, and-, and must not equal"."or".."(other dot names such as".env"or"..."are valid). - Any syntax violation ->
{"error": "invalid path"}.
- Root protection:
- Calling
"mkdir","touch","rm", or"rmdir"on"/"->{"error": "cannot modify root"}. ("ls /"is valid.)
- Calling
- Ancestor traversal (no implicit parent creation):
- Walk intermediate components
components[:-1]starting from"/":- Missing intermediate component ->
{"error": "parent directory does not exist"}. - Intermediate component is a file ->
{"error": "not a directory"}.
- Missing intermediate component ->
- Walk intermediate components
- Target operation:
mkdir <path>: If the final component already exists in the parent directory (as a file or directory) ->{"error": "path already exists"}; otherwise create an empty directory and returnTrue.touch <path>: If the final component already exists in the parent directory (as a file or directory) ->{"error": "path already exists"}; otherwise create an empty file and returnTrue.ls <path>: On"/", inspect root; otherwise if the final component does not exist ->{"error": "path does not exist"}, or if it is a file ->{"error": "not a directory"}. Return a list of direct child names sorted in standard ASCII code-point order.rm <path>: If the final component does not exist ->{"error": "path does not exist"}; if it is a directory ->{"error": "is a directory"}; otherwise delete the file and returnTrue.rmdir <path>: If the final component does not exist ->{"error": "path does not exist"}; if it is a file ->{"error": "not a directory"}; if the directory still contains any entries ->{"error": "directory not empty"}; otherwise delete the directory and returnTrue.
Examples
Example 1
Input:
commands = [
"mkdir /logs",
"touch /logs/app.log",
"mkdir /logs/archive",
"ls /logs",
"rm /logs/app.log",
"rmdir /logs/archive",
"ls /logs"
]
Output: [True, True, True, ["app.log", "archive"], True, True, []]
Walk-through:
- /logs is created, populated with file app.log and subdirectory archive, and listed in ASCII order (["app.log", "archive"]).
- Deleting app.log via rm and empty subdirectory archive via rmdir leaves /logs empty ([]).
Example 2
Input:
commands = [
"ls /",
"rmdir /",
"touch /readme.txt",
"ls /readme.txt",
"rm /readme.txt/",
"rm /readme.txt",
"ls /"
]
Output: [
[],
{"error": "cannot modify root"},
True,
{"error": "not a directory"},
{"error": "invalid path"},
True,
[]
]
Walk-through:
- "/" starts empty ([]) and rejects rmdir / with "cannot modify root".
- ls rejects file /readme.txt with "not a directory", and rm /readme.txt/ fails path validation ("invalid path") because of the trailing slash before rm /readme.txt removes the file.
Example 3
Input:
commands = [
"mkdir /src/core",
"mkdir /src",
"touch /src/main.py",
"mkdir /src/main.py",
"rmdir /src",
"ls /src"
]
Output: [
{"error": "parent directory does not exist"},
True,
True,
{"error": "path already exists"},
{"error": "directory not empty"},
["main.py"]
]
Walk-through:
- mkdir /src/core fails because /src does not exist yet.
- Once /src and /src/main.py exist, mkdir /src/main.py fails with "path already exists", rmdir /src fails with "directory not empty", and ls /src still returns ["main.py"].
Constraints
0 <= len(commands) <= 10^40 <= len(commands[i]) <= 200- Total character length across all
commandsis at most2 * 10^5.
Step-by-step walkthrough
Understand the commands and error priority
We need to implement
execute_commands(commands), which runs a list of shell-style strings on a fresh in-memory file system starting with only the root directory/. Every command produces one item in the output list:Truewhenmkdir,touch,rm, orrmdirsucceeds;- a sorted list of entry names (such as
["app.log", "archive"]) whenlssucceeds; {"error": message}when a command fails, while still continuing to execute the remaining commands.
When a single command violates two rules at once—for example
rm /missing/app.logorrm /readme.txt/—we must check conditions in a consistent order so the right error wins every time:Check order for every command: 1. Command name known? -> else "unknown command" 2. Exactly one path argument given? -> else "wrong number of arguments" 3. Path syntax strictly valid? -> else "invalid path" 4. Modifying "/" with mkdir/touch/rm/rmdir? -> "cannot modify root" 5. Every ancestor directory exists? -> else "parent directory does not exist" (or "not a directory" if an ancestor is a file) 6. Final target check: - mkdir / touch: already exists? -> "path already exists" - ls / rm / rmdir: missing? -> "path does not exist" - ls / rmdir on a file? -> "not a directory" - rm on a directory? -> "is a directory" - rmdir on a non-empty directory? -> "directory not empty"Notice two strict differences from everyday Unix shells:
touchon an existing file is an error ("path already exists"), andlson a file is an error ("not a directory").Model the file system as a tree of directories and files
A tree is a hierarchy of nodes starting from a single root node (
/), where each directory node holds named links to the files and subdirectories directly inside it.Why use a tree instead of a flat dictionary like
{"/logs": "dir", "/logs/app.log": "file"}? With a flat dictionary, listing/logsor checking whether/logsis empty inrmdir /logswould have to scan every path stored in the entire file system. In a tree, eachDirectorykeeps its ownchildrendictionary mapping each immediate child's name to either aFileor anotherDirectory:root: Directory children = { "logs": Directory children = { "app.log": File(), "archive": Directory(children={}) } }A
Filehas no contents in this problem, so an empty class is enough—isinstance(node, Directory)cleanly distinguishes directories from files. We also define a customFsErrorexception so any helper can abort immediately with a clear error message.class FsError(Exception): """Domain error raised when a file system rule fails; its text is the error message.""" class File: """Represents an empty file node; its class distinguishes it from a Directory.""" class Directory: def __init__(self) -> None: # children: maps entry name -> File or Directory, e.g. {"archive": Directory(), "app.log": File()} self.children: Dict[str, object] = {}Parse and strictly validate paths before touching the tree
Before walking the tree, we convert the raw path string into a list of component names:
"/"becomes[], and"/logs/archive"becomes["logs", "archive"].To enforce strict path rules without a tangle of special cases, we check that
pathstarts with"/"and then splitpath[1:]on"/"without stripping or filtering empty strings:path path[1:].split("/") why it passes or fails "/" [] (handled up front) valid root "/logs/archive" ["logs", "archive"] valid: every component uses allowed characters "/readme.txt/" ["readme.txt", ""] invalid: trailing slash produces "" "//logs" ["", "logs"] invalid: repeated slash produces "" "/logs/./app" ["logs", ".", "app"] invalid: "." and ".." are forbidden "logs/app" (no leading "/") invalid: relative pathBecause
parse_pathruns first in every method, malformed paths likerm /readme.txt/fail with"invalid path"even when/readme.txtexists.# Allowed characters inside a single path component (letters, digits, '.', '_', '-'). ALLOWED_NAME_CHARS = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-") def is_valid_name(name: str) -> bool: # Reject empty components (from "//" or trailing "/") and relative segments "." and "..". if name == "" or name == "." or name == "..": return False for ch in name: if ch not in ALLOWED_NAME_CHARS: return False return True def parse_path(path: str) -> List[str]: """Validate a strict absolute path and split it into component names ("/" -> []).""" if path == "/": return [] if not path.startswith("/"): raise FsError("invalid path") # Do NOT strip slashes: "/a/" -> ["a", ""] and "//a" -> ["", "a"], so is_valid_name rejects them. names = path[1:].split("/") for name in names: if not is_valid_name(name): raise FsError("invalid path") return namesWrite one path walker for strict parent resolution
Every operation after
parse_pathneeds the same thing: find the parentDirectorythat holds the final componentnames[-1]. Writing one helper_parent_of(names)that walksnames[:-1]fromself.rootsolves two problems at once:- It enforces the "no implicit parent creation" rule everywhere: if any ancestor is missing, it raises
"parent directory does not exist". - If an ancestor exists as a
File(such as/readme.txtwhen accessing/readme.txt/sub), it raises"not a directory".
For commands that require the final component to exist (
ls,rm,rmdir), a tiny companion helper_existing_child(parent, target_name)looks upnames[-1]and raises"path does not exist"if it is missing. That naturally separatesls /nope/x("parent directory does not exist") fromls /nope("path does not exist").def _parent_of(self, names: List[str]) -> Directory: """Walk names[:-1] from root without creating missing directories.""" current = self.root for ancestor_name in names[:-1]: if ancestor_name not in current.children: raise FsError("parent directory does not exist") next_node = current.children[ancestor_name] # Walking through a File (e.g. "/file/x") is always invalid. if not isinstance(next_node, Directory): raise FsError("not a directory") current = next_node return current def _existing_child(self, parent: Directory, target_name: str) -> object: """Look up the final path component inside an already-resolved parent directory.""" if target_name not in parent.children: raise FsError("path does not exist") return parent.children[target_name]- It enforces the "no implicit parent creation" rule everywhere: if any ancestor is missing, it raises
Implement mkdir, touch, ls, rm, and rmdir
Now each file system operation becomes a short, readable sequence of checks followed by a single dictionary read or write. Because every check runs before we mutate
parent.children, a failed command never leaves partial changes behind:mkdirandtouchshare_create_node: reject"/"(not names), walk toparent, verifytarget_nameis not already inparent.children, and insertDirectory()orFile().lsis the only command allowed on"/"(if not names: target = self.root). It verifiestargetis aDirectoryand returnssorted(target.children.keys()).rmandrmdirboth reject"/", resolveparentandtarget, verify the node's type (rmrejects directories;rmdirrejects files and non-empty directories), and deleteparent.children[target_name].
def _create_node(self, path: str, new_node: object) -> bool: """Shared creation flow for mkdir and touch so error priority stays identical.""" names = parse_path(path) if not names: raise FsError("cannot modify root") parent = self._parent_of(names) target_name = names[-1] # Neither mkdir nor touch may overwrite an existing file or directory. if target_name in parent.children: raise FsError("path already exists") parent.children[target_name] = new_node return True def mkdir(self, path: str) -> bool: return self._create_node(path, Directory()) def touch(self, path: str) -> bool: return self._create_node(path, File()) def ls(self, path: str) -> List[str]: names = parse_path(path) # "/" is the one path with no parent directory; ls is allowed to inspect root directly. if not names: target = self.root else: parent = self._parent_of(names) target = self._existing_child(parent, names[-1]) if not isinstance(target, Directory): raise FsError("not a directory") # Return a fresh list sorted in standard ASCII/lexicographical order. return sorted(target.children.keys()) def rm(self, path: str) -> bool: names = parse_path(path) if not names: raise FsError("cannot modify root") parent = self._parent_of(names) target_name = names[-1] target = self._existing_child(parent, target_name) # rm deletes files only; directories must be removed with rmdir. if isinstance(target, Directory): raise FsError("is a directory") del parent.children[target_name] return True def rmdir(self, path: str) -> bool: names = parse_path(path) if not names: raise FsError("cannot modify root") parent = self._parent_of(names) target_name = names[-1] target = self._existing_child(parent, target_name) if not isinstance(target, Directory): raise FsError("not a directory") # Strict rmdir refuses to delete a directory that still holds any child entries. if target.children: raise FsError("directory not empty") del parent.children[target_name] return TrueBuild a thin command dispatcher
Separating command parsing from
FileSystemmakes debugging much cleaner:FileSystemonly deals with validated paths and tree nodes, whilerun_commandhandles splitting the raw string and formatting error dictionaries.Using
command.split()(with no separator argument) splits on any run of whitespace and trims leading/trailing spaces, so" mkdir /logs "cleanly becomes["mkdir", "/logs"]while""or" "becomes[]. We catch onlyFsError—never bareException—so genuine coding mistakes still raise normal Python tracebacks during testing.def run_command(fs: FileSystem, command: str) -> object: """Parse one raw command string, invoke the matching FileSystem method, and format errors.""" # handlers: maps command keyword -> bound FileSystem method taking one path string handlers = { "mkdir": fs.mkdir, "touch": fs.touch, "ls": fs.ls, "rm": fs.rm, "rmdir": fs.rmdir, } # split() with no arguments collapses repeated spaces and trims leading/trailing whitespace. words = command.split() if not words or words[0] not in handlers: return {"error": "unknown command"} if len(words) != 2: return {"error": "wrong number of arguments"} op_name, path_arg = words[0], words[1] try: return handlers[op_name](path_arg) except FsError as error: # Catch only FsError so unexpected bugs still surface as real tracebacks during debugging. return {"error": str(error)} def execute_commands(commands: List[str]) -> List[object]: fs = FileSystem() results: List[object] = [] # Failed commands report {"error": ...} without aborting subsequent commands. for command in commands: results.append(run_command(fs, command)) return resultsTrace Example 3 step by step
Let's trace
['mkdir /src/core', 'mkdir /src', 'touch /src/main.py', 'mkdir /src/main.py', 'rmdir /src', 'ls /src']:# command names tree walkthrough output 1 mkdir /src/core ["src", "core"] _parent_of checks "src" in /: missing {"error": "parent directory does not exist"} 2 mkdir /src ["src"] parent is /; "src" added as Directory() True 3 touch /src/main.py ["src", "main.py"] parent is /src; "main.py" added as File() True 4 mkdir /src/main.py ["src", "main.py"] parent is /src; "main.py" already in /src.children {"error": "path already exists"} 5 rmdir /src ["src"] target /src is a Directory with {"main.py": ...} {"error": "directory not empty"} 6 ls /src ["src"] target /src is a Directory -> sorted(["main.py"]) ["main.py"]Notice how commands 1, 4, and 5 fail cleanly without corrupting the tree or halting command 6.
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple # Allowed characters inside a single path component (letters, digits, '.', '_', '-'). ALLOWED_NAME_CHARS = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-") class FsError(Exception): """Domain error raised when a file system rule fails; its text is the error message.""" class File: """Represents an empty file node; its class distinguishes it from a Directory.""" class Directory: def __init__(self) -> None: # children: maps entry name -> File or Directory, e.g. {"archive": Directory(), "app.log": File()} self.children: Dict[str, object] = {} def is_valid_name(name: str) -> bool: # Reject empty components (from "//" or trailing "/") and relative segments "." and "..". if name == "" or name == "." or name == "..": return False for ch in name: if ch not in ALLOWED_NAME_CHARS: return False return True def parse_path(path: str) -> List[str]: """Validate a strict absolute path and split it into component names ("/" -> []).""" if path == "/": return [] if not path.startswith("/"): raise FsError("invalid path") # Do NOT strip slashes: "/a/" -> ["a", ""] and "//a" -> ["", "a"], so is_valid_name rejects them. names = path[1:].split("/") for name in names: if not is_valid_name(name): raise FsError("invalid path") return names class FileSystem: def __init__(self) -> None: # root: single top-level Directory representing "/" self.root = Directory() def _parent_of(self, names: List[str]) -> Directory: """Walk names[:-1] from root without creating missing directories.""" current = self.root for ancestor_name in names[:-1]: if ancestor_name not in current.children: raise FsError("parent directory does not exist") next_node = current.children[ancestor_name] # Walking through a File (e.g. "/file/x") is always invalid. if not isinstance(next_node, Directory): raise FsError("not a directory") current = next_node return current def _existing_child(self, parent: Directory, target_name: str) -> object: """Look up the final path component inside an already-resolved parent directory.""" if target_name not in parent.children: raise FsError("path does not exist") return parent.children[target_name] def _create_node(self, path: str, new_node: object) -> bool: """Shared creation flow for mkdir and touch so error priority stays identical.""" names = parse_path(path) if not names: raise FsError("cannot modify root") parent = self._parent_of(names) target_name = names[-1] # Neither mkdir nor touch may overwrite an existing file or directory. if target_name in parent.children: raise FsError("path already exists") parent.children[target_name] = new_node return True def mkdir(self, path: str) -> bool: return self._create_node(path, Directory()) def touch(self, path: str) -> bool: return self._create_node(path, File()) def ls(self, path: str) -> List[str]: names = parse_path(path) # "/" is the one path with no parent directory; ls is allowed to inspect root directly. if not names: target = self.root else: parent = self._parent_of(names) target = self._existing_child(parent, names[-1]) if not isinstance(target, Directory): raise FsError("not a directory") # Return a fresh list sorted in standard ASCII/lexicographical order. return sorted(target.children.keys()) def rm(self, path: str) -> bool: names = parse_path(path) if not names: raise FsError("cannot modify root") parent = self._parent_of(names) target_name = names[-1] target = self._existing_child(parent, target_name) # rm deletes files only; directories must be removed with rmdir. if isinstance(target, Directory): raise FsError("is a directory") del parent.children[target_name] return True def rmdir(self, path: str) -> bool: names = parse_path(path) if not names: raise FsError("cannot modify root") parent = self._parent_of(names) target_name = names[-1] target = self._existing_child(parent, target_name) if not isinstance(target, Directory): raise FsError("not a directory") # Strict rmdir refuses to delete a directory that still holds any child entries. if target.children: raise FsError("directory not empty") del parent.children[target_name] return True def run_command(fs: FileSystem, command: str) -> object: """Parse one raw command string, invoke the matching FileSystem method, and format errors.""" # handlers: maps command keyword -> bound FileSystem method taking one path string handlers = { "mkdir": fs.mkdir, "touch": fs.touch, "ls": fs.ls, "rm": fs.rm, "rmdir": fs.rmdir, } # split() with no arguments collapses repeated spaces and trims leading/trailing whitespace. words = command.split() if not words or words[0] not in handlers: return {"error": "unknown command"} if len(words) != 2: return {"error": "wrong number of arguments"} op_name, path_arg = words[0], words[1] try: return handlers[op_name](path_arg) except FsError as error: # Catch only FsError so unexpected bugs still surface as real tracebacks during debugging. return {"error": str(error)} def execute_commands(commands: List[str]) -> List[object]: fs = FileSystem() results: List[object] = [] # Failed commands report {"error": ...} without aborting subsequent commands. for command in commands: results.append(run_command(fs, command)) return results✅ Submit now — all tests should pass.
Intuition & how it works
Picture a set of nested filing folders starting from one master folder labeled /. Inside each folder is an index card (a Python dictionary) that maps each item's name either to another folder (Directory) or to a blank sheet (File). This hierarchy of folders and files is a tree—a structure starting at one root node where every directory node stores named links to its immediate children. Every command follows the same two-part routine: first walk step by step from / down to the parent folder, and then inspect, add, or delete the final name on that parent folder's index card.
A tempting shortcut is to store every path in one flat dictionary like {"/logs": "dir", "/logs/app.log": "file"} instead of building a tree. That falls short as the file system grows: ls /logs and the emptiness check in rmdir /logs would have to scan every path in the entire file system in O(N) time just to see whether anything starts with "/logs/". Likewise, slicing strings separately inside each command duplicates path validation and easily mixes up error priorities (for example reporting "path does not exist" on rm /missing/app.log when "parent directory does not exist" is required). Putting path validation in one parser, ancestor traversal in one walker (_parent_of), and string splitting in a dispatcher (a thin routing function that maps a command word to its method and formats the output) keeps every rule in one place.
Here is a quick trace of 5 commands starting from an empty root /:
mkdir /logs->parse_pathyields["logs"]; parent is/, which does not have"logs"yet, so/gets"logs": Directory()and returnsTrue.touch /logs/app.log->parse_pathyields["logs", "app.log"];_parent_ofsteps into/logs, sees"app.log"is free, inserts"app.log": File(), and returnsTrue.rmdir /logs-> target/logsis aDirectory, but itschildrendictionary still contains"app.log", so it fails with{"error": "directory not empty"}.rm /logs/app.log-> walks into/logs, confirms"app.log"is aFile, deletes"app.log"from/logs.children, and returnsTrue.rmdir /logs->/logs.childrenis now empty, so"logs"is deleted fromroot.childrenand returnsTrue.
Complexity
Let L be the character length of a single command string, c be the number of entries inside the directory that ls lists, and M be the maximum length of an entry name in that directory.
- Time per
mkdir,touch,rm, orrmdir: O(L). Splitting and validating the command and path inspects each character a constant number of times, and walking the path performs one O(1)-average dictionary lookup per component name (whose lengths sum to less than L). - Time per
ls: O(L + M * c log c) (which is O(L + c log c) when entry names have bounded length). Walking to the directory takes O(L) time, and sorting its c child names in lexicographical order (character-by-character comparison by numeric ASCII code) performs O(c log c) string comparisons of up to M characters each. - Space: O(N + S) for the file system tree, where N is the number of live files and directories and S is the total characters in their stored names, plus the output list returned by
execute_commands(one result per command, with O(c) references perlscall).
Edge cases
- Root directory
/:ls /succeeds even when the file system is empty ([]), whereasmkdir /,touch /,rm /, andrmdir /all fail with"cannot modify root"regardless of whether/has children. - Strict path syntax: relative paths (
logs/app), trailing slashes (/readme.txt/), repeated slashes (//logs,/logs//app), and dot segments (/.,/..,/logs/../logs) all fail immediately with"invalid path"—even if/readme.txtor/logsexists—becauseparse_pathruns before any tree lookup. - Dots inside ordinary names: only the exact component names
"."and".."are forbidden, so names like".hidden"and"..."are valid, and ASCII sorting places"."before digits, digits before uppercase letters,"_"between uppercase and lowercase, and"a10"before"a2". - Missing ancestor vs missing target:
ls /nope/xfails during_parent_ofwith"parent directory does not exist", whereasls /nopereaches/and fails in_existing_childwith"path does not exist". - File along the path: any command whose path passes through a file (such as
mkdir /f/xorls /f/xwhen/fis a file) fails with"not a directory". - Reusing deleted names: once
rm /logs/app.logremoves a file,mkdir /logs/app.logcan reuse that name for a directory (and vice versa afterrmdir), and a recreated directory always starts empty. - Malformed commands: empty strings, whitespace-only strings, unknown verbs (
cat /logs), and uppercase verbs (MKDIR /logs) return"unknown command"; missing or extra arguments (ls,mkdir /a /b) return"wrong number of arguments", and execution continues to the next command.
Common mistakes
- Cleaning paths instead of rejecting bad ones. Calling
path.strip("/")or filtering out empty segments aftersplit("/")silently accepts"/readme.txt/"and"//logs"instead of returning"invalid path". - Implicitly creating parent directories. Auto-creating missing folders
mkdir -pstyle breaks strict validation (mkdir /src/coremust fail when/srcdoes not exist). - Checking the final name before checking ancestors. In a flat-map design, checking
if path not in kindfirst makesrm /nope/xreturn"path does not exist"instead of"parent directory does not exist". - Treating
touchon an existing file as a no-op orlson a file as[filename]. Standard Unix shells behave that way, but these strict specifications require"path already exists"and"not a directory". - Returning
list(target.children.keys())withoutsorted(...). Python dictionaries preserve insertion order, which happens to pass Example 1 (app.logcreated beforearchive) by coincidence while failing whenever entries are created out of alphabetical order. - Catching bare
Exceptioninrun_command. Wrapping the call inexcept Exceptionturns typos likeNameErrororAttributeErrorinto{"error": ...}dictionaries, making bugs much harder to diagnose than catching onlyFsError. - Using
command.split(" ")instead ofcommand.split(). Splitting on a single space turns" mkdir /logs "into empty-string tokens and wrongly triggers"wrong number of arguments".
Alternative approaches
- Flat dictionary from absolute path to node kind (
{"/": "dir", "/logs": "dir"}). Easy to write for tiny inputs (and handy as a brute-force reference oracle in tests), butlsandrmdir's emptiness check must scan all N paths in O(N) time unless you also maintain a second parent-to-children map—at which point you are maintaining a tree anyway. - Returning
(result, error)tuples instead of raisingFsError. Avoids exceptions for expected user errors, at the cost of checkingif error is not None:after every helper call (parse_path,_parent_of,_existing_child). Raising one dedicatedFsErrorand catching it at therun_commandboundary keeps each method linear and readable.
Follow-up questions
-
How could you support recursive parent creation (
mkdir -p) and subtree deletion (rm -r) while reusing the existing traversal logic? Add an optional boolean parametercreate_missing: bool = Falseto_parent_of: wheneverancestor_nameis missing andcreate_missingisTrue, insertcurrent.children[ancestor_name] = Directory()and keep walking (an existingFilealong the path still raises"not a directory").mkdir -pthen calls_parent_of(names, create_missing=True)and treats an existingDirectoryatnames[-1]asTrue(while still failing ifnames[-1]is aFile). For recursive deletion (rm -r), parse the path, reject"/", use the exact same_parent_ofand_existing_childhelpers, and simplydel parent.children[target_name]without rejecting non-empty directories—detaching that one reference drops the entire subtree (the node and all descendants nested beneath it). -
What changes are needed to store file payloads (
write/cat) and relocate an entire directory branch viamv? Addself.content: str = ""toFile:write(path, text)walks to the parent, creates aFileif missing or overwritestarget.contentif it is already aFile(failing on aDirectory), andcat(path)walks to an existingFileand returnstarget.content. Formv(src, dst), validate both paths, reject"/"for either argument, resolve both parent directories, and verify three conditions:srcexists,dstdoes not already exist, anddstis not insidesrc(checked cleanly on parsed component lists:dst_names[:len(src_names)] == src_names), which prevents detaching a directory into a cycle inside itself. Thennode = src_parent.children.pop(src_names[-1])anddst_parent.children[dst_names[-1]] = nodemoves an arbitrarily large subtree in O(L) time because child names live in the parent dictionary rather than as full paths on every descendant. -
How would you make the file system safe under concurrent multi-threaded access, and what hazards arise during cross-directory
mv? The simplest thread-safe design wraps each public method in a single coarse-grained mutex (a lock that allows only one thread at a time to execute protected code). For higher concurrency across separate branches, give eachDirectoryits own lock (ideally a readers-writer lock, which allows multiple concurrent lookups while giving directory updates exclusive access) and traverse hand over hand (acquiring the child directory's lock before releasing the parent's lock). Cross-directorymvbreaks naive per-directory locking in two ways: locking two parents in opposite orders across two concurrent moves causes a deadlock (two threads waiting forever on each other's locks), and concurrentmv /a /b/x+mv /b /a/ycan both pass their local "not insidesrc" checks before either finishes, detaching both subtrees from/; following the Linux VFS pattern—acquiring one file-system-wide rename lock before any cross-directorymv, then locking the two parents in deterministic order—prevents both bugs. -
How would you keep
lsresponsive when a single directory holds millions of entries that must be returned in sorted order? Instead of sortingtarget.childrenfrom scratch in O(c log c) on everyls, maintain child names in sorted order alongside the hash map as entries are created and removed—using a balanced binary search tree or skip list (ordered structures that keep keys sorted while supporting search, insertion, and deletion in O(log c) time). That turnsmkdir/touch/rm/rmdirinto O(L + log c) and letslsiterate already-sorted names in O(c) time. When c is in the millions, also add cursor pagination (acceptingafter_nameandlimitparameters so each call binary-searches toafter_nameand returns only the next k names in O(L + log c + k) time instead of copying millions of strings at once).
Follow-up questions
- How could you support recursive parent creation (`mkdir -p`) and subtree deletion (`rm -r`) while reusing the existing traversal logic?
- What changes are needed to store file payloads (`write` / `cat`) and relocate an entire directory branch via `mv`?
- How would you make the file system safe under concurrent multi-threaded access, and what hazards arise during cross-directory `mv`?
- How would you keep `ls` responsive when a single directory holds millions of entries that must be returned in sorted order?
Similar questions
- Virtual File System with Working Directory and Relative Paths
- Expiring Credit Balance Tracker
- Multi-Institution Personal Finance Aggregation Platform
- Personalized Content Discovery Feed Architecture
- Design a Real-Time Trending Search System
- Troubleshooting an Overloaded Kubernetes Cluster
More Perplexity interview questions
- Cascading Failures in a Task Graph Hard
- Virtual File System with Working Directory and Relative Paths Medium
- Expiring Credit Balance Tracker Medium Pro
- Multi-Institution Personal Finance Aggregation Platform Hard Pro
- Personalized Content Discovery Feed Architecture Medium Pro
- Design a Real-Time Trending Search System Medium Pro
- Troubleshooting an Overloaded Kubernetes Cluster Hard Pro
- Prerequisite-Aware Task Manager Medium Pro
- Proportional Stratified Sampling Without Replacement Medium Pro
- Design a Resilient Multi-Provider LLM Client Hard Pro