← 返回 perplexity 的题目列表Design an In-Memory Unix File System and Implement Basic Commands
类型:online_judge
Problem: Design an In-Memory Unix File System and Implement Basic Commands
Design and implement a simplified Unix-like file system that lives entirely in memory. The file system stores directories and files in a tree structure and supports the commands below.
Data Model
There are two node types: directory and file.
Every node has:
name (string)
parent (reference to parent directory; root’s parent is null)
A directory node also contains a collection/map of children indexed by name.
A file node only needs existence (no content/permissions/timestamps required).
The root directory is /.
Path Rules
Input paths are Unix style: /a/b/c.
Assume no empty segments (e.g., //) and no invalid characters.
Part 1 Commands
1) touch <path>
Create a file at the given path.
If the parent directory does not exist: return an error.
If the target already exists:
If it is a file: treat as success (no-op).
If it is a directory: return an error.
2) mkdir <path>
Create a directory at the given path.
If the parent directory does not exist: return an error.
If the target already exists:
If it is a directory: treat as success (no-op).
If it is a file: return an error.
3) ls <path>
List the contents of the given path.
If path is a directory: return the names of its direct children.
If path is a file: return a list containing only that file name.
If the path does not exist: return an error.
Output requirement:
Return names sorted in lexicographic ascending order (if unspecified, state this assumption).
Part 2 Commands
4) rm <path>
Remove a file.
Only files can be removed; if path points to a directory: return an error.
If the file does not exist: return an error.
5) rmdir <path>
Remove a directory.
Only directories can be removed.
The directory must be empty (no children) or return an error.
If the directory does not exist: return an error.
You must not remove the root directory /.
Interface Suggestion
class FileSystem:
touch(path) -> void/Result
mkdir(path) -> void/Result
ls(path) -> List[str]/Result
rm(path) -> void/Result
rmdir(path) -> void/Result
Error Handling
You may throw exceptions, return error codes, or return (success, message).
Errors should distinguish: path not found, type mismatch, directory not empty, etc.
Example (for semantics)
mkdir /a success
touch /a/f success
ls /a returns ["f"]
rm /a/f success
rmdir /a success
Example
Input
mkdir /a
ls /
Output
[a]