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:

  1. resolve_parts(cwd_parts: List[str], path: str) -> List[str]

    • Normalizes an absolute or relative path string into the canonical list of entry names below the root "/" (so "/" maps to []).
    • Raises ValueError if path == "".
    • Starts from [] when path begins with "/", or from cwd_parts for any relative path, without mutating the caller's cwd_parts list.
    • 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 to cwd_parts).
  2. 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. Raises NotADirectoryError if an ancestor component on the path is a file, or FileExistsError if the final target path is already a file.
      • write_file(path: str, content: str) -> None: Creates a file storing string content or overwrites an existing file's content. Its parent directory must already exist (FileNotFoundError if missing; NotADirectoryError if 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. Raises FileNotFoundError if any path component does not exist, NotADirectoryError if an intermediate component is a file, or IsADirectoryError if 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. Raises FileNotFoundError or NotADirectoryError for invalid paths.
      • cd(path: str) -> None: Updates the current working directory to the resolved directory. If path is 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").

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 raises ValueError.
  • Failed operations (mkdir, write_file, cd, etc.) must not corrupt existing tree entries or alter pwd().
  • Let L be the length of path, c be the length of pwd(), and k be the number of direct entries in a directory: resolve_parts, mkdir, write_file, read_file, and cd should run in O(L + c) time, and ls on a directory should run in O(L + c + k log k) time.

Step-by-step walkthrough

  1. 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 (cd and pwd) so every operation (mkdir, write_file, read_file, ls, and cd itself) 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_file overwrites an existing file. - ls behavior: 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/../logs simplifies to logs).
    • Atomic cd: if cd(path) fails for any reason, the current working directory must remain completely unchanged.
  2. 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 File and Directory as two tiny dedicated classes (rather than pretending a str is a file and a dict is a folder) makes every check readable with isinstance(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"]] = {}
    
  3. 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 helper resolve_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_parts work? With a stack (a list where you append to go one folder deeper and pop() on .. to climb one folder up): 1. If path == "", raise ValueError. 2. If path starts with "/", start from an empty stack [] (the root). Otherwise, start from a copy list(cwd_parts)—copying is crucial so pop() or append() never corrupts the live self.cwd list! 3. Split path on "/" and scan each segment: - Ignore "" (produced by leading "/", trailing "/", or "//") and "." ("current folder"). - On "..", pop the last name if parts: (if parts is 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)
    
  4. Write a single shared tree walk from the root

    Once _resolve produces canonical parts like ["workspace", "common"], every method needs to walk from self.root down those names. Write that traversal once in _walk(parts, create_dirs=False):

    • At step index, before looking up name inside node, verify isinstance(node, Directory). If node is a File (meaning someone wrote /a/file.txt/sub), raise NotADirectoryError.
    • If name is missing from node.children, raise FileNotFoundError—unless create_dirs=True (used by mkdir), in which case create node.children[name] = Directory().
    • Why can a failed mkdir never leave half-created folders behind? Think about what happens the first time _walk creates a brand-new Directory(): its children dict is empty, so every remaining segment in parts is also guaranteed missing and becomes a new Directory(). It can never collide with an existing File after 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
    
  5. Build mkdir, write_file, read_file, and ls on top of _resolve and _walk

    Because _resolve and _walk handle all string normalization and tree stepping, each file-system command becomes a short, readable check on the target node:

    • mkdir(path): walk with create_dirs=True; if the final node already existed as a File, raise FileExistsError. Calling mkdir on an existing Directory safely does nothing (idempotent—repeating the call leaves state unchanged).
    • write_file(path, content): first check if not parts: to reject "/" with IsADirectoryError("/") (avoiding parts[-1] crashing on an empty list!). Then walk to the parent directory parts[:-1] with _walk_dir, check that parts[-1] is not already a Directory, and store File(content).
    • read_file(path): walk to the node, reject Directory with IsADirectoryError, and return node.content.
    • ls(path="."): walk to the node; return [parts[-1]] if it is a File, or sorted(node.children) if it is a Directory.
        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)
    
  6. Add cwd, cd, and pwd without touching earlier methods

    Store the current directory on FileSystem as self.cwd: List[str] = [] (representing "/"). Because every method already calls self._resolve(path)—which delegates to resolve_parts(self.cwd, path)—every operation automatically supports relative paths!

    In cd(path), validate self._walk_dir(parts) before assigning self.cwd = parts. If the destination does not exist or is a File, _walk_dir raises an exception and self.cwd stays 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)
    
  7. 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() -> "/"
    
  8. 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 and O(L + c) temporary space. Splitting path on "/" scans all L characters once, copying cwd_parts for a relative path copies at most c characters' worth of folder names, and pushing/popping each segment on the parts stack is O(1) per segment.
  • mkdir, write_file, read_file, and cd: O(L + c) time. Each call runs _resolve in O(L + c) time and then steps through at most d levels of Directory.children hash-map lookups; hashing and comparing every segment name along the walk touches at most L + c characters in total.
  • ls: O(L + c + k log k) time on a directory, or O(L + c) on a file. Walking to the node takes O(L + c) time, and sorting the k entry names inside a directory takes O(k log k) string comparisons.
  • Total tree space: O(total characters of stored entry names + file contents). Each created Directory and File stores its own name key in its parent's dictionary plus its string payload, with O(L + c) temporary space per operation for the resolved parts list.

Edge cases

  • Root directory /: ls("/") starts as [], mkdir("/") is an idempotent no-op (calling it again changes nothing), cd("/") works from anywhere, and read_file("/") or write_file("/", "x") raises IsADirectoryError without crashing on an empty parts list.
  • .. at or above the root: resolve_parts(["a"], "../../..") pops "a" on the first .. and ignores the extra .. once parts is empty, clamping cleanly at / ([]).
  • Repeated and trailing slashes: //srv///api/ produces empty "" segments in split("/"), which resolve_parts skips to yield ["srv", "api"].
  • Empty path string "": Explicitly raises ValueError rather 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 mkdir leaves no partial directories: If /a/f.txt is a file, mkdir("/a/f.txt/sub") raises NotADirectoryError at f.txt before creating anything; and once _walk creates its first new empty Directory, no later step can hit an existing File.
  • Failed cd preserves pwd(): Calling cd on a missing path, a File, or "" raises before self.cwd = parts executes.

Common mistakes

  • Scattering path.split("/") across every method: Duplicating path parsing in mkdir, write_file, read_file, ls, and cd guarantees inconsistencies when relative paths, ., and .. are added.
  • Aliasing self.cwd instead of copying (parts = self.cwd): Aliasing (pointing two variables at the exact same list in memory) means parts.pop() or parts.append() mutates self.cwd immediately—corrupting pwd() even when cd("../nope") raises an error!
  • Assigning self.cwd before validating the target node: Always call _walk_dir(parts) first so invalid targets leave state untouched.
  • Popping an empty list on cd("..") at /: Forgetting if parts: before parts.pop() crashes with IndexError.
  • Not skipping empty segments from "/a".split("/"): Splitting "/a" on "/" produces ["", "a"]; forgetting if segment == "": continue inserts a phantom folder named "" above "a".
  • Indexing parts[-1] in write_file("/") without a root check: Because / resolves to parts = [], parts[-1] raises IndexError instead of IsADirectoryError.

Alternative approaches

  • Node pointer with parent links for cwd: Store self.cwd_node: Directory with a parent reference on every Directory (root.parent = root). Stepping into ".." becomes node = node.parent during the walk itself, which naturally rejects ghost/../logs when ghost does not exist and survives renaming an ancestor folder, at the cost of maintaining parent pointers and name fields on every directory node.
  • Flat dictionary mapping absolute path strings to nodes ({"/": None, "/srv": None, "/srv/config.json": "{}"}): Makes read_file a single dictionary lookup after normalizing the path string, but slows ls(dir) and recursive rm(dir) down to O(total_nodes) scans across the entire file system.

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? Implement rm(path) by resolving parts, rejecting parts == [] (you cannot delete /), walking to parent = _walk_dir(parts[:-1]), and deleting parent.children[parts[-1]] (refusing non-empty directories unless a recursive=True flag is set). Because self.cwd is stored as a list of names, deleting the current directory (or any ancestor where self.cwd[:len(parts)] == parts) would leave self.cwd dangling at a ghost path that raises FileNotFoundError on relative commands—or worse, silently rebinds if a new folder with the same name is created later! The cleanest interview design either refuses to delete cwd or its ancestors (raise PermissionError / OSError) or explicitly falls back self.cwd to /, while noting that real Unix kernels let a process stay inside an unlinked directory inode whose relative lookups fail with ENOENT.
  • If multiple concurrent user sessions operate against the same underlying file tree with independent working directories, how would you restructure state ownership? Move self.cwd out of FileSystem and into a lightweight per-user (or per-process) Session / ShellContext object that holds a reference to the shared FileSystem tree plus its own cwd: List[str], mirroring how an operating system kernel stores one shared directory tree alongside per-process working directories. Every Session method resolves its path via resolve_parts(self.cwd, path) and passes canonical parts into the shared FileSystem, which now protects tree reads and writes with a reader-writer lock and re-validates cwd on 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/shortcut is 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 an ELOOP-style error) so cycles like p -> q and q -> p cannot loop forever.
  • How would you extend path navigation to support ~ home-directory expansion and cd - for toggling back to the prior working directory? Pass home_parts (such as ["users", "maya"]) into the resolver and treat "~" specially only when it is the very first segment (path == "~" or path.startswith("~/")), seeding the initial stack with list(home_parts) instead of [] or list(cwd_parts) while leaving "src/~" as an ordinary folder named "~". To support cd - (jump back to the previous directory, like OLDPWD in bash), store self.prev_cwd: Optional[List[str]] = None on FileSystem: when cd("-") is called, raise ValueError if prev_cwd is None, otherwise validate _walk_dir(self.prev_cwd) and swap self.cwd, self.prev_cwd = self.prev_cwd, self.cwd—updating prev_cwd on normal cd calls only after _walk_dir succeeds.

Follow-up questions

Similar questions

More Perplexity interview questions

All 13 Perplexity questions →