Coding — Software Engineer
Build a Unix-inspired file system that exists entirely in memory. The interview format presents this as a two-stage implementation task, with command-style APIs resembling a standard in-memory file-system design exercise.
Create a class that works with absolute paths, including /, /var, and /var/log.txt.
class InMemoryUnixFileSystem:
def touch(self, path: str) -> None:
"""Create an empty file if it does not already exist."""
def mkdir(self, path: str) -> None:
"""Create a directory."""
def ls(self, path: str) -> list[str]:
"""List a directory, or return the file name if path is a file."""
def rm(self, path: str) -> bool:
"""Remove a file. Return True if a file was removed."""
def rmdir(self, path: str) -> bool:
"""Remove an empty directory. Return True if a directory was removed."""
/./ characters and a final / should be normalized; for example, /x///y/ represents the same location as /x/y.mkdir(path) has mkdir -p semantics, so it creates any absent directories along the route.touch(path) may add a file only when its parent directory is already present.ls("/") produces the root directory's child names in lexicographical order.ls on a file returns a list containing only that file's name.rm(path) is limited to file deletion and must not delete a directory.rmdir(path) succeeds only for empty directories; it must reject both / and directories that still contain entries.touch("/") is not allowed, since / identifies the root directory rather than a file.Implement the following behavior:
fs = InMemoryUnixFileSystem()
fs.mkdir("/projects/api")
fs.touch("/projects/api/main.py")
fs.touch("/projects/NOTES.txt")
fs.ls("/") # ["projects"]
fs.ls("/projects") # ["NOTES.txt", "api"]
fs.ls("/projects/api") # ["main.py"]
fs.ls("/projects/api/main.py") # ["main.py"]
Add support for the deletion operations.
fs.rm("/projects/api/main.py") # True
fs.ls("/projects/api") # []
fs.rmdir("/projects/api") # True
fs.ls("/projects") # ["NOTES.txt"]
fs.rmdir("/projects") # False, NOTES.txt still exists inside it
fs.rm("/projects") # False, this path names a directory
fs.rm("/projects/NOTES.txt") # True
fs.rmdir("/projects") # True
Important cases to test include:
/touch at a location where a directory already existsmkdir at a location where a file already existsrmdir for a directory that is not empty[object Object]