Virtual File System with Working Directory and Relative Paths
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Design and implement an in-memory hierarchical file system that supports creating directories, reading and writing text files, listing directory contents, tracking a current working directory (cd and pwd), and resolving both absolute and relative paths across every operation.
Implement resolve_parts and FileSystem matching the signatures in starter.py:
-
resolve_parts(cwd_parts: List[str], path: str) -> List[str]- Normalizes an absolute or relative
pathstring into the canonical list of entry names below the root"/"(so"/"maps to[]). - Raises
ValueErrorifpath == "". - Starts from
[]whenpathbegins with"/", or fromcwd_partsfor any relative path, without mutating the caller'scwd_partslist. - Ignores empty segments produced by leading, trailing, or consecutive slashes (such as
"//srv///api/") as well as"."segments. - Pops the most recent directory name on
".."; if already at the root ([]),".."stays at[]. - Performs purely lexical normalization without inspecting the directory tree (for instance,
"ghost/../logs"normalizes to"logs"relative tocwd_parts).
- Normalizes an absolute or relative
-
FileSystem- Initializes with an empty root directory
"/"and sets the initial working directory to"/". - Every operation accepts both absolute paths (
"/srv/api") and relative paths ("v1","./v1","../common/utils.py"), resolved against the current working directory:mkdir(path: str) -> None: Creates the target directory along with any missing parent directories. If the target directory already exists, does nothing. RaisesNotADirectoryErrorif an ancestor component on the path is a file, orFileExistsErrorif the final target path is already a file.write_file(path: str, content: str) -> None: Creates a file storing stringcontentor overwrites an existing file's content. Its parent directory must already exist (FileNotFoundErrorif missing;NotADirectoryErrorif an ancestor or parent component is a file), and the target path itself must not be an existing directory, including"/"(IsADirectoryError).read_file(path: str) -> str: Returns the string content of an existing file. RaisesFileNotFoundErrorif any path component does not exist,NotADirectoryErrorif an intermediate component is a file, orIsADirectoryErrorif the target is a directory.ls(path: str = ".") -> List[str]: Defaults to"."(the current working directory). Returns immediate entry names in lexicographically sorted order when the target is a directory, or[file_name]when the target is a file. RaisesFileNotFoundErrororNotADirectoryErrorfor invalid paths.cd(path: str) -> None: Updates the current working directory to the resolved directory. Ifpathis empty (ValueError), missing (FileNotFoundError), or resolves to or traverses through a file (NotADirectoryError), raises the corresponding exception and leaves the current working directory unchanged.pwd() -> str: Formats the current working directory as a canonical absolute path (such as"/"or"/workspace/backend").
- Initializes with an empty root directory
Examples
Example 1
Input:
fs = FileSystem()
fs.mkdir("/srv/api/v1")
fs.write_file("/srv/api/config.json", '{"port":8080}')
fs.write_file("/srv/api/config.json", '{"port":9090}')
print(fs.ls("/srv/api"))
print(fs.ls("/srv/api/config.json"))
print(fs.read_file("/srv/api/config.json"))
Output:
['config.json', 'v1']
['config.json']
{"port":9090}
Walk-through: mkdir("/srv/api/v1") creates /srv, /srv/api, and /srv/api/v1 in one call. The second write_file overwrites config.json with '{"port":9090}'. Calling ls on directory /srv/api returns its entries sorted alphabetically (['config.json', 'v1']), whereas calling ls directly on file /srv/api/config.json returns a single-element list with that file's name (['config.json']).
Example 2
Input:
fs = FileSystem()
fs.mkdir("/workspace/backend")
fs.mkdir("/workspace/common")
fs.cd("workspace/backend")
print(fs.pwd())
fs.write_file("../common/utils.py", "v2")
print(fs.ls(".."))
print(fs.read_file("./../../workspace//common/utils.py"))
try:
fs.cd("../common/utils.py")
except NotADirectoryError:
print("kept:", fs.pwd())
fs.cd("../../../..")
print(fs.pwd())
Output:
/workspace/backend
['backend', 'common']
v2
kept: /workspace/backend
/
Walk-through: Starting from /, cd("workspace/backend") moves the working directory to /workspace/backend. From there, write_file("../common/utils.py", "v2") steps up to /workspace and writes utils.py inside common. Attempting to cd into file utils.py raises NotADirectoryError without altering pwd(). Finally, cd("../../../..") climbs past the top of the tree and clamps cleanly at /.
Constraints
- Path strings consist of ASCII letters, digits, dots (
.), underscores (_), hyphens (-), and forward slashes (/). - Only exact segments
"."and".."have special navigation meaning; names such as"..."or".env"are ordinary file or directory names. - Passing
""to any path parameter raisesValueError. - Failed operations (
mkdir,write_file,cd, etc.) must not corrupt existing tree entries or alterpwd(). - Let
Lbe the length ofpath,cbe the length ofpwd(), andkbe the number of direct entries in a directory:resolve_parts,mkdir,write_file,read_file, andcdshould run inO(L + c)time, andlson a directory should run inO(L + c + k log k)time.
Step-by-step walkthrough
Agree on edge cases and error contracts before writing code
This problem combines two layers: first a hierarchical file system supporting directories, text files, and sorted listings over absolute paths (
/srv/api/config.json), and second a working-directory layer (cdandpwd) so every operation (mkdir,write_file,read_file,ls, andcditself) also works with relative paths (src/app.py,./src,../common/utils.py).Before touching code, pin down exact contracts for edge cases and errors: - File writes: contents are strings, and
write_fileoverwrites an existing file. -lsbehavior: returns sorted entry names for a directory,[file_name]for a single file, and defaults to"."(the current directory) when called with no arguments. - Exception types: use Python's standard file-system exceptions so callers know why a call failed:Exception When it is raised ----------------------------------------------------------------------------------- FileNotFoundError A path segment does not exist (e.g. read_file("/missing")) NotADirectoryError A File is used where a Directory is required (e.g. cd("utils.py")) IsADirectoryError A Directory is used where a File is required (e.g. read_file("/")) FileExistsError mkdir targets an existing File (e.g. mkdir("/srv/api/config.json")) ValueError The path string is completely empty ""- Slash &
..rules: repeated or trailing slashes (//srv///api/) collapse cleanly to/srv/api;..at the root/stays at/just like a Unix shell; and..is normalized lexically before walking the tree (ghost/../logssimplifies tologs). - Atomic
cd: ifcd(path)fails for any reason, the current working directory must remain completely unchanged.
- Slash &
Model the hierarchy with explicit File and Directory nodes
A file system is a tree—a hierarchy starting at a single root folder
/where each folder maps entry names to child folders or files:root "/" (Directory) │ "workspace" (Directory) ╱ ╲ "backend" (Directory) "common" (Directory) │ │ "src" (Directory) "utils.py" -> File("v2")Representing
FileandDirectoryas two tiny dedicated classes (rather than pretending astris a file and adictis a folder) makes every check readable withisinstance(node, Directory)and prevents bugs if files later gain metadata like timestamps or permissions.from typing import Dict, Union class File: """A leaf node in the file-system tree that stores string content.""" def __init__(self, content: str) -> None: # content: plain string payload of the file, e.g. "hello world" self.content = content class Directory: """An internal tree node mapping entry names to child File or Directory nodes.""" def __init__(self) -> None: # children: maps single entry name -> File or Directory, e.g. {"api": Directory(), "config.json": File("{}")} self.children: Dict[str, Union[File, "Directory"]] = {}Isolate all path string parsing in one stack-based resolver
Here is the single biggest architectural lesson of adding relative paths: if five methods each call
path.split("/")on their own, supporting relative paths forces you to rewrite five methods—and missing one creates subtle bugs. Instead, put all string parsing inside a single pure helperresolve_parts(cwd_parts, path)that turns any path into a canonical path (a clean list of folder/file names below/, such as["workspace", "common", "utils.py"], with all.,.., and extra slashes removed).How does
resolve_partswork? With a stack (a list where you append to go one folder deeper andpop()on..to climb one folder up): 1. Ifpath == "", raiseValueError. 2. Ifpathstarts with"/", start from an empty stack[](the root). Otherwise, start from a copylist(cwd_parts)—copying is crucial sopop()orappend()never corrupts the liveself.cwdlist! 3. Splitpathon"/"and scan each segment: - Ignore""(produced by leading"/", trailing"/", or"//") and"."("current folder"). - On"..", pop the last nameif parts:(ifpartsis already[], stay at root). - Otherwise, append the segment name.Trace: cwd_parts = ["workspace", "backend"], path = "../common/./utils.py/" Start (relative copy) -> ["workspace", "backend"] segment ".." -> pop! ["workspace"] segment "common" -> push! ["workspace", "common"] segment "." -> skip ["workspace", "common"] segment "utils.py" -> push! ["workspace", "common", "utils.py"] segment "" -> skip ["workspace", "common", "utils.py"]from typing import List def resolve_parts(cwd_parts: List[str], path: str) -> List[str]: """Convert any absolute or relative path string into canonical names below '/'.""" # Reject "" explicitly because "" is not a valid path (use "." for current directory). if path == "": raise ValueError("empty path") # Phase 1: choose starting stack — "/" starts at root [], relative starts at a COPY of cwd_parts. if path.startswith("/"): parts: List[str] = [] else: # Copy cwd_parts so '..' pops or new appends never mutate the caller's live working directory. parts = list(cwd_parts) # Phase 2: normalize each slash-separated segment using stack push/pop rules. for segment in path.split("/"): # Skip "" (caused by leading "/", trailing "/", or "//") and "." ("stay in current folder"). if segment == "" or segment == ".": continue if segment == "..": # At root (parts == []), ".." stays at root just like a Unix shell. if parts: parts.pop() else: parts.append(segment) return parts def to_path(parts: List[str]) -> str: """Format canonical parts back into an absolute path: ['workspace', 'backend'] -> '/workspace/backend', [] -> '/'.""" return "/" + "/".join(parts)Write a single shared tree walk from the root
Once
_resolveproduces canonicalpartslike["workspace", "common"], every method needs to walk fromself.rootdown those names. Write that traversal once in_walk(parts, create_dirs=False):- At step
index, before looking upnameinsidenode, verifyisinstance(node, Directory). Ifnodeis aFile(meaning someone wrote/a/file.txt/sub), raiseNotADirectoryError. - If
nameis missing fromnode.children, raiseFileNotFoundError—unlesscreate_dirs=True(used bymkdir), in which case createnode.children[name] = Directory(). - Why can a failed
mkdirnever leave half-created folders behind? Think about what happens the first time_walkcreates a brand-newDirectory(): itschildrendict is empty, so every remaining segment inpartsis also guaranteed missing and becomes a newDirectory(). It can never collide with an existingFileafter creating its first directory!
def _walk(self, parts: List[str], create_dirs: bool = False) -> Union[File, Directory]: """Walk from root along canonical parts and return the target File or Directory node.""" node: Union[File, Directory] = self.root for index, name in enumerate(parts): # You cannot step inside a File (e.g. "/a/file.txt/sub") — fail with NotADirectoryError. if not isinstance(node, Directory): raise NotADirectoryError(to_path(parts[:index])) if name not in node.children: if not create_dirs: raise FileNotFoundError(to_path(parts[: index + 1])) # Once we create a fresh empty Directory here, every remaining name in parts is also # guaranteed missing, so mkdir can never hit a File later and leave partial state. node.children[name] = Directory() node = node.children[name] return node def _walk_dir(self, parts: List[str]) -> Directory: """Walk to target node and verify that the final destination itself is a Directory.""" node = self._walk(parts) if not isinstance(node, Directory): raise NotADirectoryError(to_path(parts)) return node- At step
Build mkdir, write_file, read_file, and ls on top of _resolve and _walk
Because
_resolveand_walkhandle all string normalization and tree stepping, each file-system command becomes a short, readable check on the target node:mkdir(path): walk withcreate_dirs=True; if the final node already existed as aFile, raiseFileExistsError. Callingmkdiron an existingDirectorysafely does nothing (idempotent—repeating the call leaves state unchanged).write_file(path, content): first checkif not parts:to reject"/"withIsADirectoryError("/")(avoidingparts[-1]crashing on an empty list!). Then walk to the parent directoryparts[:-1]with_walk_dir, check thatparts[-1]is not already aDirectory, and storeFile(content).read_file(path): walk to the node, rejectDirectorywithIsADirectoryError, and returnnode.content.ls(path="."): walk to the node; return[parts[-1]]if it is aFile, orsorted(node.children)if it is aDirectory.
def mkdir(self, path: str) -> None: """Create directory and any missing parent directories; no-op if directory already exists.""" parts = self._resolve(path) node = self._walk(parts, create_dirs=True) # If the final target already existed as a File (e.g. mkdir("/a/file.txt")), reject it. if isinstance(node, File): raise FileExistsError(to_path(parts)) def write_file(self, path: str, content: str) -> None: """Create a file or overwrite an existing file inside an already-existing parent directory.""" parts = self._resolve(path) # Guard root "/" before indexing parts[-1], since "/" has no parent and is always a directory. if not parts: raise IsADirectoryError("/") parent_dir = self._walk_dir(parts[:-1]) file_name = parts[-1] # Writing file content over an existing Directory of the same name is illegal. if isinstance(parent_dir.children.get(file_name), Directory): raise IsADirectoryError(to_path(parts)) parent_dir.children[file_name] = File(content) def read_file(self, path: str) -> str: """Return the string content of an existing File.""" parts = self._resolve(path) node = self._walk(parts) if isinstance(node, Directory): raise IsADirectoryError(to_path(parts)) return node.content def ls(self, path: str = ".") -> List[str]: """Return sorted child names for a Directory, or [file_name] when path names a File.""" parts = self._resolve(path) node = self._walk(parts) if isinstance(node, File): # Root "/" is always a Directory, so a File is guaranteed to have parts[-1]. return [parts[-1]] return sorted(node.children)Add cwd, cd, and pwd without touching earlier methods
Store the current directory on
FileSystemasself.cwd: List[str] = [](representing"/"). Because every method already callsself._resolve(path)—which delegates toresolve_parts(self.cwd, path)—every operation automatically supports relative paths!In
cd(path), validateself._walk_dir(parts)before assigningself.cwd = parts. If the destination does not exist or is aFile,_walk_dirraises an exception andself.cwdstays untouched.def __init__(self) -> None: # root: top-level "/" Directory node of the entire tree self.root = Directory() # cwd: canonical folder names from "/" to current working directory; [] means "/" self.cwd: List[str] = [] def _resolve(self, path: str) -> List[str]: """Single choke point that turns any user path string into canonical parts.""" return resolve_parts(self.cwd, path) def cd(self, path: str) -> None: """Change current working directory; keep self.cwd unchanged if validation raises.""" parts = self._resolve(path) # Validate target exists and is a Directory BEFORE updating self.cwd. self._walk_dir(parts) self.cwd = parts def pwd(self) -> str: """Return the current working directory formatted as an absolute path.""" return to_path(self.cwd)Walk through Example 2 step by step
Trace Example 2 to verify relative resolution, error preservation, and clamping at root:
Call self.cwd Action / Return ----------------------------------------------------------------------------------------------------------- fs = FileSystem() [] pwd() -> "/" fs.mkdir("/workspace/backend") [] creates /workspace and /workspace/backend fs.mkdir("/workspace/common") [] creates /workspace/common fs.cd("workspace/backend") ["workspace", "backend"] pwd() -> "/workspace/backend" fs.write_file("../common/utils.py", "v2") ["workspace", "backend"] writes File("v2") at /workspace/common/utils.py fs.ls("..") ["workspace", "backend"] resolves ["workspace"] -> ["backend", "common"] fs.cd("../common/utils.py") ["workspace", "backend"] _walk_dir raises NotADirectoryError; self.cwd is STILL ["workspace", "backend"]! fs.cd("../../../..") [] clamps at root; pwd() -> "/"Complete solution
from typing import Dict, List, Union class File: """A leaf node in the file-system tree that stores string content.""" def __init__(self, content: str) -> None: # content: plain string payload of the file, e.g. "hello world" self.content = content class Directory: """An internal tree node mapping entry names to child File or Directory nodes.""" def __init__(self) -> None: # children: maps single entry name -> File or Directory, e.g. {"api": Directory(), "config.json": File("{}")} self.children: Dict[str, Union[File, "Directory"]] = {} def resolve_parts(cwd_parts: List[str], path: str) -> List[str]: """Convert any absolute or relative path string into canonical names below '/'.""" # Reject "" explicitly because "" is not a valid path (use "." for current directory). if path == "": raise ValueError("empty path") # Phase 1: choose starting stack — "/" starts at root [], relative starts at a COPY of cwd_parts. if path.startswith("/"): parts: List[str] = [] else: # Copy cwd_parts so '..' pops or new appends never mutate the caller's live working directory. parts = list(cwd_parts) # Phase 2: normalize each slash-separated segment using stack push/pop rules. for segment in path.split("/"): # Skip "" (caused by leading "/", trailing "/", or "//") and "." ("stay in current folder"). if segment == "" or segment == ".": continue if segment == "..": # At root (parts == []), ".." stays at root just like a Unix shell. if parts: parts.pop() else: parts.append(segment) return parts def to_path(parts: List[str]) -> str: """Format canonical parts back into an absolute path: ['workspace', 'backend'] -> '/workspace/backend', [] -> '/'.""" return "/" + "/".join(parts) class FileSystem: """In-memory hierarchical file system supporting absolute paths, relative paths, and cd/pwd.""" def __init__(self) -> None: # root: top-level "/" Directory node of the entire tree self.root = Directory() # cwd: canonical folder names from "/" to current working directory; [] means "/" self.cwd: List[str] = [] def _resolve(self, path: str) -> List[str]: """Single choke point that turns any user path string into canonical parts.""" return resolve_parts(self.cwd, path) def _walk(self, parts: List[str], create_dirs: bool = False) -> Union[File, Directory]: """Walk from root along canonical parts and return the target File or Directory node.""" node: Union[File, Directory] = self.root for index, name in enumerate(parts): # You cannot step inside a File (e.g. "/a/file.txt/sub") — fail with NotADirectoryError. if not isinstance(node, Directory): raise NotADirectoryError(to_path(parts[:index])) if name not in node.children: if not create_dirs: raise FileNotFoundError(to_path(parts[: index + 1])) # Once we create a fresh empty Directory here, every remaining name in parts is also # guaranteed missing, so mkdir can never hit a File later and leave partial state. node.children[name] = Directory() node = node.children[name] return node def _walk_dir(self, parts: List[str]) -> Directory: """Walk to target node and verify that the final destination itself is a Directory.""" node = self._walk(parts) if not isinstance(node, Directory): raise NotADirectoryError(to_path(parts)) return node def mkdir(self, path: str) -> None: """Create directory and any missing parent directories; no-op if directory already exists.""" parts = self._resolve(path) node = self._walk(parts, create_dirs=True) # If the final target already existed as a File (e.g. mkdir("/a/file.txt")), reject it. if isinstance(node, File): raise FileExistsError(to_path(parts)) def write_file(self, path: str, content: str) -> None: """Create a file or overwrite an existing file inside an already-existing parent directory.""" parts = self._resolve(path) # Guard root "/" before indexing parts[-1], since "/" has no parent and is always a directory. if not parts: raise IsADirectoryError("/") parent_dir = self._walk_dir(parts[:-1]) file_name = parts[-1] # Writing file content over an existing Directory of the same name is illegal. if isinstance(parent_dir.children.get(file_name), Directory): raise IsADirectoryError(to_path(parts)) parent_dir.children[file_name] = File(content) def read_file(self, path: str) -> str: """Return the string content of an existing File.""" parts = self._resolve(path) node = self._walk(parts) if isinstance(node, Directory): raise IsADirectoryError(to_path(parts)) return node.content def ls(self, path: str = ".") -> List[str]: """Return sorted child names for a Directory, or [file_name] when path names a File.""" parts = self._resolve(path) node = self._walk(parts) if isinstance(node, File): # Root "/" is always a Directory, so a File is guaranteed to have parts[-1]. return [parts[-1]] return sorted(node.children) def cd(self, path: str) -> None: """Change current working directory; keep self.cwd unchanged if validation raises.""" parts = self._resolve(path) # Validate target exists and is a Directory BEFORE updating self.cwd. self._walk_dir(parts) self.cwd = parts def pwd(self) -> str: """Return the current working directory formatted as an absolute path.""" return to_path(self.cwd)✅ Submit now — all tests should pass.
Intuition & how it works
Think of an in-memory file system as two cleanly separated pieces: a cabinet of nested folders (Directory and File tree nodes) and a breadcrumb trail (self.cwd) tracking which folder you are currently standing inside. Whenever any command receives a path string, a single translator (resolve_parts) uses a stack (a list where normal names push onto the end and .. pops the last name off) to turn messy input like ../common/./utils.py into a canonical path—a clean list of folder names starting from the root /, such as ["workspace", "common", "utils.py"]. After that translation, the folder tree only ever walks clean lists from /.
Two naive shortcuts cause bugs when cd and relative paths enter the picture. First, if mkdir, write_file, read_file, and ls each call path.split("/") separately, retrofitting relative paths forces edits in five places—and forgetting even one (like write_file's parent lookup) breaks relative writes. Second, trying to glue strings together (cwd + "/" + path) without normalizing ., .., and // treats /workspace/backend/../common and /workspace/common as two completely different keys, or mutates self.cwd mid-flight before checking whether a cd target actually exists.
Walk through Example 2 starting at /:
- Setup: mkdir("/workspace/backend") and mkdir("/workspace/common") build "workspace" under root, with children "backend" and "common". Calling cd("workspace/backend") resolves ["workspace", "backend"], verifies it is a Directory, and sets self.cwd = ["workspace", "backend"].
- Relative write: Calling write_file("../common/utils.py", "v2") copies ["workspace", "backend"], pops "backend" on "..", appends "common" and "utils.py" to get ["workspace", "common", "utils.py"], walks root -> workspace -> common, and stores File("v2") under "utils.py".
- Safe failure: Calling cd("../common/utils.py") resolves ["workspace", "common", "utils.py"] on a fresh copy and calls _walk_dir, which raises NotADirectoryError before self.cwd is reassigned—so pwd() safely stays "/workspace/backend".
Complexity
Let L be the character length of the input path, c be the character length of the current working directory (pwd()), d be the number of segments in the resolved canonical path, and k be the number of direct children inside a listed directory.
resolve_parts:O(L + c)time andO(L + c)temporary space. Splittingpathon"/"scans allLcharacters once, copyingcwd_partsfor a relative path copies at mostccharacters' worth of folder names, and pushing/popping each segment on thepartsstack isO(1)per segment.mkdir,write_file,read_file, andcd:O(L + c)time. Each call runs_resolveinO(L + c)time and then steps through at mostdlevels ofDirectory.childrenhash-map lookups; hashing and comparing every segment name along the walk touches at mostL + ccharacters in total.ls:O(L + c + k log k)time on a directory, orO(L + c)on a file. Walking to the node takesO(L + c)time, and sorting thekentry names inside a directory takesO(k log k)string comparisons.- Total tree space:
O(total characters of stored entry names + file contents). Each createdDirectoryandFilestores its own name key in its parent's dictionary plus its string payload, withO(L + c)temporary space per operation for the resolvedpartslist.
Edge cases
- Root directory
/:ls("/")starts as[],mkdir("/")is an idempotent no-op (calling it again changes nothing),cd("/")works from anywhere, andread_file("/")orwrite_file("/", "x")raisesIsADirectoryErrorwithout crashing on an emptypartslist. ..at or above the root:resolve_parts(["a"], "../../..")pops"a"on the first..and ignores the extra..oncepartsis empty, clamping cleanly at/([]).- Repeated and trailing slashes:
//srv///api/produces empty""segments insplit("/"), whichresolve_partsskips to yield["srv", "api"]. - Empty path string
"": Explicitly raisesValueErrorrather than silently acting like"/"or".". - Dot-like names (
"...",".gitignore"): Only exact"."and".."are special; three dots"..."or hidden file names like".env"are treated as ordinary entry names. - Failed
mkdirleaves no partial directories: If/a/f.txtis a file,mkdir("/a/f.txt/sub")raisesNotADirectoryErroratf.txtbefore creating anything; and once_walkcreates its first new emptyDirectory, no later step can hit an existingFile. - Failed
cdpreservespwd(): Callingcdon a missing path, aFile, or""raises beforeself.cwd = partsexecutes.
Common mistakes
- Scattering
path.split("/")across every method: Duplicating path parsing inmkdir,write_file,read_file,ls, andcdguarantees inconsistencies when relative paths,., and..are added. - Aliasing
self.cwdinstead of copying (parts = self.cwd): Aliasing (pointing two variables at the exact same list in memory) meansparts.pop()orparts.append()mutatesself.cwdimmediately—corruptingpwd()even whencd("../nope")raises an error! - Assigning
self.cwdbefore validating the target node: Always call_walk_dir(parts)first so invalid targets leave state untouched. - Popping an empty list on
cd("..")at/: Forgettingif parts:beforeparts.pop()crashes withIndexError. - Not skipping empty segments from
"/a".split("/"): Splitting"/a"on"/"produces["", "a"]; forgettingif segment == "": continueinserts a phantom folder named""above"a". - Indexing
parts[-1]inwrite_file("/")without a root check: Because/resolves toparts = [],parts[-1]raisesIndexErrorinstead ofIsADirectoryError.
Alternative approaches
- Node pointer with
parentlinks forcwd: Storeself.cwd_node: Directorywith aparentreference on everyDirectory(root.parent = root). Stepping into".."becomesnode = node.parentduring the walk itself, which naturally rejectsghost/../logswhenghostdoes not exist and survives renaming an ancestor folder, at the cost of maintainingparentpointers andnamefields on every directory node. - Flat dictionary mapping absolute path strings to nodes (
{"/": None, "/srv": None, "/srv/config.json": "{}"}): Makesread_filea single dictionary lookup after normalizing the path string, but slowsls(dir)and recursiverm(dir)down toO(total_nodes)scans across the entire file system.
Follow-up questions
- Suppose you introduce an
rmoperation—how should the system behave when a caller deletes the active working directory or one of its ancestors? Implementrm(path)by resolvingparts, rejectingparts == [](you cannot delete/), walking toparent = _walk_dir(parts[:-1]), and deletingparent.children[parts[-1]](refusing non-empty directories unless arecursive=Trueflag is set). Becauseself.cwdis stored as a list of names, deleting the current directory (or any ancestor whereself.cwd[:len(parts)] == parts) would leaveself.cwddangling at a ghost path that raisesFileNotFoundErroron relative commands—or worse, silently rebinds if a new folder with the same name is created later! The cleanest interview design either refuses to deletecwdor its ancestors (raise PermissionError/OSError) or explicitly falls backself.cwdto/, while noting that real Unix kernels let a process stay inside an unlinked directory inode whose relative lookups fail withENOENT. - If multiple concurrent user sessions operate against the same underlying file tree with independent working directories, how would you restructure state ownership? Move
self.cwdout ofFileSystemand into a lightweight per-user (or per-process)Session/ShellContextobject that holds a reference to the sharedFileSystemtree plus its owncwd: List[str], mirroring how an operating system kernel stores one shared directory tree alongside per-process working directories. EverySessionmethod resolves its path viaresolve_parts(self.cwd, path)and passes canonicalpartsinto the sharedFileSystem, which now protects tree reads and writes with a reader-writer lock and re-validatescwdon each command in case another session removed that directory. - Once symbolic links exist in the tree, why does purely lexical
..normalization break down, and how should path resolution work instead? A symbolic link (symlink) is a special node that redirects lookups to another target path; if/a/shortcutis a symlink pointing to/x/y, then/a/shortcut/..physically means the parent of/x/y(which is/x), whereas purely lexical..cancels"shortcut"and lands in/a! To resolve paths physically, walk the tree segment by segment while maintaining a stack of real reached directory names: when you hit a symlink, splice its target segments ahead of the remaining segments (resetting the stack to[]if the symlink target starts with"/"), pop the stack when you hit"..", and cap total symlink expansions (for example at 40 hops, raising anELOOP-style error) so cycles likep -> qandq -> pcannot loop forever. - How would you extend path navigation to support
~home-directory expansion andcd -for toggling back to the prior working directory? Passhome_parts(such as["users", "maya"]) into the resolver and treat"~"specially only when it is the very first segment (path == "~"orpath.startswith("~/")), seeding the initial stack withlist(home_parts)instead of[]orlist(cwd_parts)while leaving"src/~"as an ordinary folder named"~". To supportcd -(jump back to the previous directory, likeOLDPWDin bash), storeself.prev_cwd: Optional[List[str]] = NoneonFileSystem: whencd("-")is called, raiseValueErrorifprev_cwdisNone, otherwise validate_walk_dir(self.prev_cwd)and swapself.cwd, self.prev_cwd = self.prev_cwd, self.cwd—updatingprev_cwdon normalcdcalls only after_walk_dirsucceeds.
Follow-up questions
- Suppose you introduce an `rm` operation—how should the system behave when a caller deletes the active working directory or one of its ancestors?
- If multiple concurrent user sessions operate against the same underlying file tree with independent working directories, how would you restructure state ownership?
- Once symbolic links exist in the tree, why does purely lexical `..` normalization break down, and how should path resolution work instead?
- How would you extend path navigation to support `~` home-directory expansion and `cd -` for toggling back to the prior working directory?
Similar questions
- Strict In-Memory Directory Tree and Shell Command Interpreter
- 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
- Strict In-Memory Directory Tree and Shell Command Interpreter Hard
- Cascading Failures in a Task Graph Hard
- 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