Simulate cd over an in-memory filesystem with symbolic links and cycle detection

Quick Overview

Implement a class that simulates the Unix cd command over an in-memory filesystem of directories and symbolic links, with mkdir, ln, cd and pwd. It tests resolving absolute and relative paths with . and .., following link targets from the right directory, and detecting symlink cycles without changing state on failure.

Simulate cd over an in-memory filesystem with symbolic links and cycle detection

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design a stateful class that simulates the Unix `cd` command over an in-memory filesystem made of directories and symbolic links. The class keeps a current working directory, which starts at `/`, and resolves `cd(path)` for absolute paths (starting with `/`), relative paths, and the special components `.` (current directory) and `..` (parent directory). Symbolic links are followed transparently during resolution, and a link's target may itself contain `.`, `..`, absolute or relative components. A relative target is read from the directory that contains the link. When `cd` passes through a link, the working directory becomes the directory the link resolves to, so `pwd` prints that directory's real path and a later `..` moves to its real parent. Cycles introduced by symbolic links must be detected: when one is found, `cd` returns `False` and leaves the current directory unchanged. Implement these methods: - `mkdir(path: str) -> bool` creates a directory at the given absolute path, creating any missing intermediate directories. It returns `True` on success and `False` if a non-directory node already occupies a component along the path. - `ln(link_path: str, target: str) -> bool` creates a symbolic link at the absolute `link_path` that points to `target`, which may be absolute or relative. Intermediate directories must already exist. It returns `True` on success and `False` if the parent does not exist or a node already exists at `link_path`. - `cd(path: str) -> bool` changes the current working directory to `path` (absolute or relative), following symbolic links and resolving `.` and `..`. It returns `True` on success, and `False` without changing state if the path is invalid or a symlink cycle is detected. - `pwd() -> str` returns the absolute path of the current working directory, starting with `/`. Example 1 (directories only): ```text Input: ["CDWithSymbolicLinks", "mkdir", "mkdir", "cd", "pwd", "cd", "pwd", "cd", "pwd", "cd", "pwd"] [[], ["/a/b/c"], ["/a/x"], ["/a/b"], [], ["c"], [], ["../x"], [], ["../../.."], []] Output: [null, true, true, true, "/a/b", true, "/a/b/c", false, "/a/b/c", true, "/"] ``` ```text fs = CDWithSymbolicLinks() # cwd = / fs.mkdir("/a/b/c") # True (creates /a, /a/b, /a/b/c) fs.mkdir("/a/x") # True (creates /a/x) fs.cd("/a/b") # True (absolute cd) fs.pwd() # "/a/b" fs.cd("c") # True (relative cd into c) fs.pwd() # "/a/b/c" fs.cd("../x") # False (from /a/b/c, .. is /a/b, which has no x) fs.pwd() # "/a/b/c" (unchanged) fs.cd("../../..") # True (walks up to /) fs.pwd() # "/" ``` Example 2 (symbolic links and a cycle): ```text fs = CDWithSymbolicLinks() fs.mkdir("/a/b/c") # True fs.mkdir("/x/y") # True fs.ln("/a/b/toY", "/x/y") # True (absolute target) fs.ln("/x/up", "../a/b") # True (relative target, read from /x) fs.cd("/a/b/toY") # True (follows the link to /x/y) fs.pwd() # "/x/y" fs.cd("../up/c") # True (.. is /x, up leads to /a/b, then c) fs.pwd() # "/a/b/c" fs.ln("/a/p", "q") # True fs.ln("/a/q", "p") # True fs.cd("/a/p") # False (p points to q, q points back to p) fs.pwd() # "/a/b/c" (unchanged) ``` ```hint Failing without side effects Every failure case must leave the working directory where it was. Think about where the result of the walk should live until you know the whole path resolved. ``` ```hint When a repeat is a loop Following the same link twice is not always a cycle: with `l` pointing to `.`, the path `l/l` resolves fine. Ask what is different about the state when a walk really can never finish. ``` ### Constraints & Assumptions - Paths use `/` as the separator. - Absolute paths begin with `/`; relative paths do not. - `.` refers to the current directory and `..` to the parent directory. - `cd ..` from the root `/` stays at the root. - If `cd(path)` meets a missing component, a symlink cycle, or a link that fails to resolve, it returns `False` and leaves the current directory unchanged. - Every filesystem entry is a directory or a symbolic link. There are no regular files. ### Clarifying Questions to Ask - May `ln` create a link whose target does not exist yet, so the problem only shows up when a `cd` goes through it? - Should `mkdir` treat a symbolic link in the middle of its path as a conflict, or follow it? - Should repeated slashes such as `/a//b` and a trailing slash be accepted and read as single separators? - Is there a cap on how many links a single `cd` may follow, as real kernels have? ### What a Strong Answer Covers - A node model that separates directories from links and keeps parent pointers, so `..` and `pwd` work without storing path strings. - Correct resolution of absolute and relative paths, `.`, `..` at the root, and relative link targets read from the link's own directory. - Cycle detection that rejects real loops and still allows the same link to be followed more than once in one path. - A `cd` that computes the destination first and commits it only on success, covering missing names, dangling links and cycles. - The cost of `cd`, including how chains of links can multiply the work. ### Follow-up Questions - How would you change the design so `pwd` shows the logical path through the links, the way a shell's `cd -L` does? - A chain of links can make one `cd` walk exponentially many components. How would you bound that cost? - How would `rm` and `mv` fit into this model, and what should happen to links, or to the working directory, when their target is removed? - How would you write the resolver without recursion?

Overview: Implement a class that simulates the Unix cd command over an in-memory filesystem of directories and symbolic links, with mkdir, ln, cd and pwd. It tests resolving absolute and relative paths with . and .., following link targets from the right directory, and detecting symlink cycles without changing state on failure.

General logo
General
Nov 24, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design a stateful class that simulates the Unix cd command over an in-memory filesystem made of directories and symbolic links.

The class keeps a current working directory, which starts at /, and resolves cd(path) for absolute paths (starting with /), relative paths, and the special components . (current directory) and .. (parent directory).

Symbolic links are followed transparently during resolution, and a link's target may itself contain ., .., absolute or relative components. A relative target is read from the directory that contains the link. When cd passes through a link, the working directory becomes the directory the link resolves to, so pwd prints that directory's real path and a later .. moves to its real parent. Cycles introduced by symbolic links must be detected: when one is found, cd returns False and leaves the current directory unchanged.

Implement these methods:

  • mkdir(path: str) -> bool creates a directory at the given absolute path, creating any missing intermediate directories. It returns True on success and False if a non-directory node already occupies a component along the path.
  • ln(link_path: str, target: str) -> bool creates a symbolic link at the absolute link_path that points to target , which may be absolute or relative. Intermediate directories must already exist. It returns True on success and False if the parent does not exist or a node already exists at link_path .
  • cd(path: str) -> bool changes the current working directory to path (absolute or relative), following symbolic links and resolving . and .. . It returns True on success, and False without changing state if the path is invalid or a symlink cycle is detected.
  • pwd() -> str returns the absolute path of the current working directory, starting with / .

Example 1 (directories only):

Input:
["CDWithSymbolicLinks", "mkdir",    "mkdir",  "cd",     "pwd", "cd",  "pwd", "cd",     "pwd", "cd",         "pwd"]
[[],                    ["/a/b/c"], ["/a/x"], ["/a/b"], [],    ["c"], [],    ["../x"], [],    ["../../.."], []]

Output: [null, true, true, true, "/a/b", true, "/a/b/c", false, "/a/b/c", true, "/"]
fs = CDWithSymbolicLinks()    # cwd = /
fs.mkdir("/a/b/c")            # True     (creates /a, /a/b, /a/b/c)
fs.mkdir("/a/x")              # True     (creates /a/x)
fs.cd("/a/b")                 # True     (absolute cd)
fs.pwd()                      # "/a/b"
fs.cd("c")                    # True     (relative cd into c)
fs.pwd()                      # "/a/b/c"
fs.cd("../x")                 # False    (from /a/b/c, .. is /a/b, which has no x)
fs.pwd()                      # "/a/b/c" (unchanged)
fs.cd("../../..")             # True     (walks up to /)
fs.pwd()                      # "/"

Example 2 (symbolic links and a cycle):

fs = CDWithSymbolicLinks()
fs.mkdir("/a/b/c")            # True
fs.mkdir("/x/y")              # True
fs.ln("/a/b/toY", "/x/y")     # True     (absolute target)
fs.ln("/x/up", "../a/b")      # True     (relative target, read from /x)
fs.cd("/a/b/toY")             # True     (follows the link to /x/y)
fs.pwd()                      # "/x/y"
fs.cd("../up/c")              # True     (.. is /x, up leads to /a/b, then c)
fs.pwd()                      # "/a/b/c"
fs.ln("/a/p", "q")            # True
fs.ln("/a/q", "p")            # True
fs.cd("/a/p")                 # False    (p points to q, q points back to p)
fs.pwd()                      # "/a/b/c" (unchanged)

Constraints & Assumptions

  • Paths use / as the separator.
  • Absolute paths begin with / ; relative paths do not.
  • . refers to the current directory and .. to the parent directory.
  • cd .. from the root / stays at the root.
  • If cd(path) meets a missing component, a symlink cycle, or a link that fails to resolve, it returns False and leaves the current directory unchanged.
  • Every filesystem entry is a directory or a symbolic link. There are no regular files.

Clarifying Questions to Ask Guidance

  • May ln create a link whose target does not exist yet, so the problem only shows up when a cd goes through it?
  • Should mkdir treat a symbolic link in the middle of its path as a conflict, or follow it?
  • Should repeated slashes such as /a//b and a trailing slash be accepted and read as single separators?
  • Is there a cap on how many links a single cd may follow, as real kernels have?

What a Strong Answer Covers Guidance

  • A node model that separates directories from links and keeps parent pointers, so .. and pwd work without storing path strings.
  • Correct resolution of absolute and relative paths, . , .. at the root, and relative link targets read from the link's own directory.
  • Cycle detection that rejects real loops and still allows the same link to be followed more than once in one path.
  • A cd that computes the destination first and commits it only on success, covering missing names, dangling links and cycles.
  • The cost of cd , including how chains of links can multiply the work.

Follow-up Questions Guidance

  • How would you change the design so pwd shows the logical path through the links, the way a shell's cd -L does?
  • A chain of links can make one cd walk exponentially many components. How would you bound that cost?
  • How would rm and mv fit into this model, and what should happen to links, or to the working directory, when their target is removed?
  • How would you write the resolver without recursion?