Implement Core Linux Commands on an In-Memory File System

Quick Overview

Build an in-memory Unix-style file system that supports pwd, cd, mkdir, ls, touch, echo, cat and rm with absolute and relative paths, including . and .. components. It tests tree modeling, a shared path resolver, and careful error handling for missing entries and wrong entry types.

Implement Core Linux Commands on an In-Memory File System

Company: Midjourney

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design an in-memory simulation of a Unix-like file system that supports a subset of core Linux shell commands. The system starts at the root directory `/` with an empty tree and tracks a current working directory that changes as the user navigates. The file system must support both absolute paths (starting with `/`) and relative paths (resolved against the current working directory). It must also handle the special path components `.` (current directory) and `..` (parent directory). Each entry in the tree is either a directory (which may contain children) or a file (which stores plain text content). Commands that operate on the wrong entry type (for example `cd` on a file or `cat` on a directory) should return an appropriate error string. Implement the following methods: - `pwd() -> str`: Return the absolute path of the current working directory. - `cd(path: str) -> str`: Change the current working directory to `path`. Returns an empty string on success or an error message on failure. - `mkdir(path: str) -> str`: Create a new directory at `path`. Returns an empty string on success or an error message if the entry already exists. - `ls(path: str) -> List[str]`: List entries at `path` (or the current directory if `path` is empty) in lexicographic order. - `touch(path: str) -> str`: Create an empty file at `path` if it does not exist; otherwise no-op. Returns an empty string on success. - `echo(content: str, path: str) -> str`: Write `content` to the file at `path`, creating the file if necessary (overwrite semantics). Returns an empty string on success or an error message on failure. - `cat(path: str) -> str`: Return the content of the file at `path`, or an error message if the path is invalid or refers to a directory. - `rm(path: str) -> str`: Remove the file or directory (and its subtree) at `path`. Returns an empty string on success or an error message on failure. Example 1: ```text Input: ["LinuxFileSystem", "pwd", "mkdir", "mkdir", "cd", "pwd", "touch", "echo", "cat", "ls"] [[], [], ["/home"], ["/home/user"], ["/home/user"], [], ["notes.txt"], ["hello world", "notes.txt"], ["notes.txt"], [""]] Output: [null, "/", "", "", "", "/home/user", "", "", "hello world", ["notes.txt"]] Explanation: fs = LinuxFileSystem() # cwd = / fs.pwd() # '/' fs.mkdir('/home') # tree: /home fs.mkdir('/home/user') # tree: /home/user fs.cd('/home/user') # cwd = /home/user fs.pwd() # '/home/user' fs.touch('notes.txt') # creates empty file fs.echo('hello world', 'notes.txt') # writes content fs.cat('notes.txt') # 'hello world' fs.ls('') # ['notes.txt'] ``` Example 2: ```text Input: ["LinuxFileSystem", "mkdir", "mkdir", "cd", "touch", "touch", "ls", "rm", "ls", "cd", "pwd"] [[], ["/a"], ["/a/b"], ["/a/b"], ["x"], ["y"], [""], ["x"], [""], [".."], []] Output: [null, "", "", "", "", "", ["x", "y"], "", ["y"], "", "/a"] Explanation: fs = LinuxFileSystem() # cwd = / fs.mkdir('/a') # tree: /a fs.mkdir('/a/b') # tree: /a/b fs.cd('/a/b') # cwd = /a/b fs.touch('x') # creates /a/b/x fs.touch('y') # creates /a/b/y fs.ls('') # ['x', 'y'] (sorted) fs.rm('x') # removes /a/b/x fs.ls('') # ['y'] fs.cd('..') # cwd = /a fs.pwd() # '/a' ``` ```hint One walk for every command Nearly every command starts by turning a path into a tree node. Write that walk once, choosing the starting node from the first character of the path, and make every command call it. ``` ```hint The last component `mkdir`, `touch`, `echo` and `rm` act on an entry that may not exist yet. Think about what they need to find first, and which paths have no name left to create or remove. ``` ### Constraints & Assumptions - All paths use `/` as the separator and may be absolute or relative. - Path components contain only alphanumeric characters, `.`, `_`, and `-`. - Maximum directory depth is `100`. - Maximum number of total entries (files + directories) is `10⁴`. - File content size does not exceed `10⁴` characters. - Method names are lowercase and match the Linux command names. ### Clarifying Questions to Ask - Should `mkdir` create missing parent directories (like `mkdir -p`), or fail when the parent does not exist? Do `touch` and `echo` follow the same rule? - What should `ls` return when `path` is a file, and what does it return on an error, given that its return type is a list? - What happens to the current working directory when `rm` removes it or one of its ancestors? - Is a specific format required for error strings, or is any non-empty message acceptable? ### What a Strong Answer Covers - A tree model that tells directories from files, and how `..` and `pwd` move toward the root. - One shared path resolver for absolute and relative paths, including `.`, `..` at the root, and repeated slashes. - Missing-entry and wrong-type errors for each command, such as `cd` on a file, `cat` on a directory, or a missing parent. - The behavior of `rm` on a non-empty directory and on the current directory or one of its ancestors. - The time per command in terms of path length and depth, plus the sorting cost of `ls`. ### Follow-up Questions - How would you add `mkdir -p`, so that missing parent directories are created along the way? - How would you implement `mv` for files and directories, and how do you stop a directory from being moved inside its own subtree? - A file can contain text that looks like an error message. How would you change the API so `cat` callers can always tell content from failure? - How would you support several shell sessions, each with its own working directory, sharing one tree?

Overview: Build an in-memory Unix-style file system that supports pwd, cd, mkdir, ls, touch, echo, cat and rm with absolute and relative paths, including . and .. components. It tests tree modeling, a shared path resolver, and careful error handling for missing entries and wrong entry types.

Midjourney logo
Midjourney
Nov 25, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design an in-memory simulation of a Unix-like file system that supports a subset of core Linux shell commands. The system starts at the root directory / with an empty tree and tracks a current working directory that changes as the user navigates.

The file system must support both absolute paths (starting with /) and relative paths (resolved against the current working directory). It must also handle the special path components . (current directory) and .. (parent directory).

Each entry in the tree is either a directory (which may contain children) or a file (which stores plain text content). Commands that operate on the wrong entry type (for example cd on a file or cat on a directory) should return an appropriate error string.

Implement the following methods:

  • pwd() -> str : Return the absolute path of the current working directory.
  • cd(path: str) -> str : Change the current working directory to path . Returns an empty string on success or an error message on failure.
  • mkdir(path: str) -> str : Create a new directory at path . Returns an empty string on success or an error message if the entry already exists.
  • ls(path: str) -> List[str] : List entries at path (or the current directory if path is empty) in lexicographic order.
  • touch(path: str) -> str : Create an empty file at path if it does not exist; otherwise no-op. Returns an empty string on success.
  • echo(content: str, path: str) -> str : Write content to the file at path , creating the file if necessary (overwrite semantics). Returns an empty string on success or an error message on failure.
  • cat(path: str) -> str : Return the content of the file at path , or an error message if the path is invalid or refers to a directory.
  • rm(path: str) -> str : Remove the file or directory (and its subtree) at path . Returns an empty string on success or an error message on failure.

Example 1:

Input:
["LinuxFileSystem", "pwd", "mkdir",   "mkdir",        "cd",           "pwd", "touch",       "echo",                       "cat",         "ls"]
[[],                [],    ["/home"], ["/home/user"], ["/home/user"], [],    ["notes.txt"], ["hello world", "notes.txt"], ["notes.txt"], [""]]

Output: [null, "/", "", "", "", "/home/user", "", "", "hello world", ["notes.txt"]]

Explanation:
fs = LinuxFileSystem()                       # cwd = /
fs.pwd()                                     # '/'
fs.mkdir('/home')                            # tree: /home
fs.mkdir('/home/user')                       # tree: /home/user
fs.cd('/home/user')                          # cwd = /home/user
fs.pwd()                                     # '/home/user'
fs.touch('notes.txt')                        # creates empty file
fs.echo('hello world', 'notes.txt')          # writes content
fs.cat('notes.txt')                          # 'hello world'
fs.ls('')                                    # ['notes.txt']

Example 2:

Input:
["LinuxFileSystem", "mkdir", "mkdir",  "cd",     "touch", "touch", "ls", "rm",  "ls", "cd",   "pwd"]
[[],                ["/a"],  ["/a/b"], ["/a/b"], ["x"],   ["y"],   [""], ["x"], [""], [".."], []]

Output: [null, "", "", "", "", "", ["x", "y"], "", ["y"], "", "/a"]

Explanation:
fs = LinuxFileSystem()                       # cwd = /
fs.mkdir('/a')                               # tree: /a
fs.mkdir('/a/b')                             # tree: /a/b
fs.cd('/a/b')                                # cwd = /a/b
fs.touch('x')                                # creates /a/b/x
fs.touch('y')                                # creates /a/b/y
fs.ls('')                                    # ['x', 'y']  (sorted)
fs.rm('x')                                   # removes /a/b/x
fs.ls('')                                    # ['y']
fs.cd('..')                                  # cwd = /a
fs.pwd()                                     # '/a'

Constraints & Assumptions

  • All paths use / as the separator and may be absolute or relative.
  • Path components contain only alphanumeric characters, . , _ , and - .
  • Maximum directory depth is 100 .
  • Maximum number of total entries (files + directories) is 10⁴ .
  • File content size does not exceed 10⁴ characters.
  • Method names are lowercase and match the Linux command names.

Clarifying Questions to Ask Guidance

  • Should mkdir create missing parent directories (like mkdir -p ), or fail when the parent does not exist? Do touch and echo follow the same rule?
  • What should ls return when path is a file, and what does it return on an error, given that its return type is a list?
  • What happens to the current working directory when rm removes it or one of its ancestors?
  • Is a specific format required for error strings, or is any non-empty message acceptable?

What a Strong Answer Covers Guidance

  • A tree model that tells directories from files, and how .. and pwd move toward the root.
  • One shared path resolver for absolute and relative paths, including . , .. at the root, and repeated slashes.
  • Missing-entry and wrong-type errors for each command, such as cd on a file, cat on a directory, or a missing parent.
  • The behavior of rm on a non-empty directory and on the current directory or one of its ancestors.
  • The time per command in terms of path length and depth, plus the sorting cost of ls .

Follow-up Questions Guidance

  • How would you add mkdir -p , so that missing parent directories are created along the way?
  • How would you implement mv for files and directories, and how do you stop a directory from being moved inside its own subtree?
  • A file can contain text that looks like an error message. How would you change the API so cat callers can always tell content from failure?
  • How would you support several shell sessions, each with its own working directory, sharing one tree?