Katkat

Implement a hierarchical file store

AnthropicSoftware Engineer · Onsite

Last updated

This problem tests your ability to design a hierarchical file system data structure and implement operations for directory traversal, file manipulation, and path normalization.

Problem Statement

Design a memory-resident hierarchical file system. The system should support basic file operations using absolute and relative paths.

Implement the following interface:

  • mkdir(path: str): Creates a new directory at the specified path. Returns True if successful, False if a file already exists at that location or the parent path does not exist.
  • touch(path: str, content: str): Creates a file at the specified path with the given content. If the file exists, overwrite the content.
  • read(path: str): Returns the content of the file. If the path does not exist or refers to a directory, return an error indicator (e.g., None).
  • ls(path: str): Lists the contents of a directory. Return a sorted list of names. If path is a file, return a list containing only that filename.
  • rm(path: str): Deletes the file or directory. If it is a directory, remove all its descendants.

Constraints

  • Paths are strings like /home/user/docs/file.txt.
  • You must handle the root directory /.
  • Assume path components contain alphanumeric characters only.

Examples

fs = FileSystem()
fs.mkdir("/data")
fs.touch("/data/notes.txt", "hello world")
print(fs.ls("/data")) # Output: ["notes.txt"]
print(fs.read("/data/notes.txt")) # Output: "hello world"

Edge Cases

  • Creating a file in a non-existent directory.
  • Deleting the root directory.
  • Repeated path separators (e.g., //home///user).

Hints

Hint 1

Use a Trie-like structure (an N-ary tree) where each node represents a directory or file.

Hint 2

Store nodes in a dictionary mapping names to child nodes to allow O(1) lookup of path components.

Hint 3

Implement a helper function to split paths by '/' and ignore empty strings caused by consecutive slashes.

Follow-up questions

  • How would you modify your design to support file permissions (e.g., read/write/execute for owner/group/others)?
  • If this system needs to persist to disk, what serialization strategy would you use to minimize recovery time?
  • How would you handle concurrent access to the file system using locks or atomic operations?