588. Design In-Memory File System
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to design an in-memory file system that mimics the behavior of a real file system. We need to implement functionalities for listing directory contents (ls), creating directories (mkdir), adding content to files (addContentToFile), and reading content from files (readContentFromFile). The file system is structured hierarchically with paths starting from a root directory /. This hierarchical nature strongly suggests a tree-based data structure.
Solution
Design In-Memory File System in Python
import collections
class FileSystem:
def __init__(self):
# The Trie node structure. isFile distinguishes files from directories.
# content stores file content. children is a dict for sub-directories/files.
def TrieNode():
return {'isFile': False, 'content': '', 'children': collections.defaultdict(TrieNode)}
self.root = TrieNode()
def ls(self, path: str) -> List[str]:
# Parse path into components, filtering out empty strings from splitting '/'
components = [p for p in path.split('/') if p]
curr = self.root
for component in components:
curr = curr['children'][component]
if curr['isFile']:
# If it's a file, return its name, which is the last component of the path.
return [components[-1]]
else:
# If it's a directory, return sorted names of its children.
return sorted(curr['children'].keys())
def mkdir(self, path: str) -> None:
components = [p for p in path.split('/') if p]
curr = self.root
for component in components:
# defaultdict automatically creates a new TrieNode if key doesn't exist.
curr = curr['children'][component]
def addContentToFile(self, filePath: str, content: str) -> None:
components = [p for p in filePath.split('/') if p]
curr = self.root
# Traverse to parent directory.
for component in components[:-1]:
curr = curr['children'][component]
fileName = components[-1]
# Get the file node (defaultdict creates if not present).
fileNode = curr['children'][fileName]
fileNode['isFile'] = True
fileNode['content'] += content
def readContentFromFile(self, filePath: str) -> str:
components = [p for p in filePath.split('/') if p]
curr = self.root
for component in components:
curr = curr['children'][component]
return curr['content']
Design In-Memory File System in Java
class FileSystem {
// Node represents a file or a directory.
class Node {
boolean isFile = false;
// Using TreeMap to keep children sorted lexicographically.
Map<String, Node> children = new TreeMap<>();
StringBuilder content = new StringBuilder();
}
private Node root;
public FileSystem() {
root = new Node();
}
public List<String> ls(String path) {
Node curr = findNode(path);
List<String> result = new ArrayList<>();
if (curr.isFile) {
// If path points to a file, return the file name.
result.add(path.substring(path.lastIndexOf('/') + 1));
} else {
// If path points to a directory, return its children's names.
result.addAll(curr.children.keySet());
}
return result;
}
public void mkdir(String path) {
String[] components = path.split("/");
Node curr = root;
// Start from 1 because components[0] is empty for absolute paths.
for (int i = 1; i < components.length; i++) {
curr.children.putIfAbsent(components[i], new Node());
curr = curr.children.get(components[i]);
}
}
public void addContentToFile(String filePath, String content) {
String[] components = filePath.split("/");
Node curr = root;
// Traverse to the parent directory.
for (int i = 1; i < components.length - 1; i++) {
curr = curr.children.get(components[i]);
}
String fileName = components[components.length - 1];
// Find or create the file node.
curr.children.putIfAbsent(fileName, new Node());
Node fileNode = curr.children.get(fileName);
// Mark it as a file and append content.
fileNode.isFile = true;
fileNode.content.append(content);
}
public String readContentFromFile(String filePath) {
Node node = findNode(filePath);
return node.content.toString();
}
// Helper to find the node at a given path.
private Node findNode(String path) {
if (path.equals("/")) {
return root;
}
String[] components = path.split("/");
Node curr = root;
// Start from 1 because components[0] is empty.
for (int i = 1; i < components.length; i++) {
curr = curr.children.get(components[i]);
}
return curr;
}
}
Design In-Memory File System in C++
class FileSystem {
private:
// Node represents a file or a directory in the file system.
struct Node {
bool is_file = false;
string content;
map<string, Node*> children; // Using map to keep children sorted lexicographically.
// Destructor to clean up allocated memory for children nodes.
~Node() {
for (auto& pair : children) {
delete pair.second;
}
}
};
Node* root;
// Helper function to split a string by a delimiter.
vector<string> split(const string& s, char delimiter) {
vector<string> tokens;
string token;
istringstream tokenStream(s);
// We ignore the first token as it's empty for absolute paths like "/a/b".
getline(tokenStream, token, delimiter);
while (getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
public:
FileSystem() {
root = new Node();
}
~FileSystem() {
delete root;
}
vector<string> ls(string path) {
Node* curr = root;
if (path != "/") {
vector<string> components = split(path, '/');
for (const string& component : components) {
curr = curr->children[component];
}
}
if (curr->is_file) {
// If it's a file, return its name.
size_t last_slash = path.find_last_of('/');
return {path.substr(last_slash + 1)};
}
// If it's a directory, return names of its children.
vector<string> result;
for (auto const& [name, node] : curr->children) {
result.push_back(name);
}
return result;
}
void mkdir(string path) {
vector<string> components = split(path, '/');
Node* curr = root;
for (const string& component : components) {
if (curr->children.find(component) == curr->children.end()) {
curr->children[component] = new Node();
}
curr = curr->children[component];
}
}
void addContentToFile(string filePath, string content) {
vector<string> components = split(filePath, '/');
Node* curr = root;
// Traverse to the parent directory.
for (size_t i = 0; i < components.size() - 1; ++i) {
curr = curr->children[components[i]];
}
string filename = components.back();
if (curr->children.find(filename) == curr->children.end()) {
curr->children[filename] = new Node();
}
curr = curr->children[filename];
curr->is_file = true;
curr->content += content;
}
string readContentFromFile(string filePath) {
vector<string> components = split(filePath, '/');
Node* curr = root;
for (const string& component : components) {
curr = curr->children[component];
}
return curr->content;
}
};
Design In-Memory File System in TypeScript
class FileSystem {
// Using a nested class for the Trie Node for encapsulation.
private FNode: new () => {
isFile: boolean;
content: string;
children: Map<string, any>;
};
private root: any;
constructor() {
// The Trie node structure.
this.FNode = class {
isFile = false;
content = "";
children: Map<string, any> = new Map();
};
this.root = new this.FNode();
}
ls(path: string): string[] {
// Filter out empty strings that result from splitting the path.
const components = path.split('/').filter(p => p.length > 0);
let curr = this.root;
for (const component of components) {
curr = curr.children.get(component);
}
if (curr.isFile) {
// If it's a file, return its name (the last path component).
return [components[components.length - 1]];
} else {
// If it's a directory, return sorted list of children names.
return [...curr.children.keys()].sort();
}
}
mkdir(path: string): void {
const components = path.split('/').filter(p => p.length > 0);
let curr = this.root;
for (const component of components) {
if (!curr.children.has(component)) {
curr.children.set(component, new this.FNode());
}
curr = curr.children.get(component);
}
}
addContentToFile(filePath: string, content: string): void {
const components = filePath.split('/').filter(p => p.length > 0);
let curr = this.root;
// Traverse to the parent directory.
for (let i = 0; i < components.length - 1; i++) {
curr = curr.children.get(components[i]);
}
const fileName = components[components.length - 1];
if (!curr.children.has(fileName)) {
curr.children.set(fileName, new this.FNode());
}
const fileNode = curr.children.get(fileName);
fileNode.isFile = true;
fileNode.content += content;
}
readContentFromFile(filePath: string): string {
const components = filePath.split('/').filter(p => p.length > 0);
let curr = this.root;
for (const component of components) {
curr = curr.children.get(component);
}
return curr.content;
}
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.