Implement an In-Memory File System
eBaySoftware Engineer · Online AssessmentLast updated
This problem tests proficiency with hierarchical data structures (trees/tries) and object-oriented design by requiring the implementation of an in-memory file system with file/directory management and path resolution.
Problem Statement
Design an in-memory file system that supports basic file and directory operations. Your system should be represented as a tree structure where each node is either a file or a directory.
API Requirements
void mkdir(string path): Create a new directory at the given path. The parent directories must exist.void addContentToFile(string filePath, string content): If the file does not exist, create it and append the content. If it exists, append the content.string readContentFromFile(string filePath): Return the content of the file at the given path.List ls(string path): If the path is a file, return a list containing only the file name. If it is a directory, return a sorted list of names of the files and directories in that path.
Constraints
- Paths are absolute and start with '/'.
- Directory names and file names contain only lowercase English letters.
- The root directory '/' is always present.
Examples
// Example 1:
fs.mkdir("/a/b/c");
fs.addContentToFile("/a/b/c/d", "hello");
fs.ls("/a/b/c"); // returns ["d"]
fs.readContentFromFile("/a/b/c/d"); // returns "hello"
// Example 2:
fs.ls("/"); // returns ["a"]
Edge Cases
- Accessing paths that don't exist.
- Performing operations on the root directory.
- Adding content to a directory path instead of a file.
Hints
Hint 1
Use a Trie-like data structure where each node represents either a file or a directory and contains a map to its children.
Hint 2
Store the content in the file-type nodes and a boolean flag to distinguish between files and directories.
Hint 3
Split the path string by '/' to traverse the tree level by level until you reach the target node.
Follow-up questions
- How would you modify this system to support 'rm' (removing files or directories recursively)?
- How would you implement file permissions (e.g., read, write, execute) for different users?
- If the file system needed to be persistent, how would you approach serializing the tree structure to disk?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.