Build a Virtual Directory Tree with File Operations
Data Structure DesignAuto-graded · 13 test casesLast updated
Design and implement a tree-based in-memory filesystem supporting directory creation, file I/O, listing, and deletion via absolute paths.
Design an in-memory virtual filesystem that organizes directories and files in a hierarchical tree structure. Your implementation must process a sequence of filesystem commands and return their results.
Implement a function that accepts two parallel lists:
operations: command names as stringsarguments: corresponding argument lists for each command
The function returns a list of results, one per operation.
Supported Commands
mkdir — arguments: [path]
- Creates a directory at the given absolute path
- Returns
Trueif created successfully - Returns
Falseif:- A file already exists at that path
- The parent directory does not exist
- The path is the root directory
/
touch — arguments: [path, content]
- Creates or overwrites a file at the specified path with the given content string
- Returns
None(always) - Does nothing if the parent directory is missing or if the path points to an existing directory
read — arguments: [path]
- Returns the content string of the file at the specified path
- Returns
Noneif the path does not exist or points to a directory
ls — arguments: [path]
- Returns a sorted list of entry names within the directory
- If the path points to a file, returns a single-element list containing only that file's name
- Returns an empty list if the path does not exist
rm — arguments: [path]
- Deletes the file or directory at the path (recursively removes all descendants if it's a directory)
- Returns
None(always) - Does nothing if the path does not exist or is the root directory
Path Rules
- All paths are absolute, starting with
/ - The root directory
/always exists and cannot be deleted - Path components are separated by
/and consist of alphanumeric characters, dots, or underscores - Multiple consecutive slashes are treated as a single separator (e.g.,
//home///userequals/home/user)
Constraints
- 1 ≤ number of operations ≤ 1000
- 1 ≤ path length ≤ 200
- 0 ≤ content length ≤ 1000
- All paths are absolute (start with
/) - Operation names are valid (one of the five commands above)
Examples
Example 1
Input: virtual_filesystem(['mkdir', 'touch', 'ls', 'read'], [['/data'], ['/data/notes.txt', 'hello world'], ['/data'], ['/data/notes.txt']])
Output: [True, None, ['notes.txt'], 'hello world']
Hints
Hint 1
Model the filesystem as a tree where each node is either a directory (containing a map of children) or a file (containing content).
Hint 2
Parse each path into components by splitting on slashes and filtering empty strings to handle consecutive separators.
Hint 3
For mutations like mkdir and touch, navigate to the parent directory first, then manipulate the target name in the parent's children map.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the filesystem as an N-ary tree where each node represents either a directory or a file. Directory nodes maintain a dictionary mapping child names to child nodes, while file nodes store content strings.
The solution breaks down into three key components:
-
Path Parsing: Convert path strings into component lists by splitting on
/and filtering out empty strings. This normalization handles edge cases like consecutive slashes (//home///userbecomes["home", "user"]). -
Tree Traversal: Walk from the root node through successive children following the path components. Return
Noneif any component is missing or if we attempt to traverse through a file node. -
Operation Dispatch: For each command, parse the path, locate the relevant node(s), and perform the appropriate mutation or query. Creation operations (
mkdir,touch) navigate to the parent directory and manipulate the target entry in the parent's children dictionary.
Correctness
The tree structure enforces the hierarchical invariant: only directory nodes have children, and files are leaves. Path normalization ensures every valid path maps to exactly one node, preventing inconsistencies from malformed paths.
For mutations, checking the parent node's existence and type before modification prevents creating entries under non-existent or file paths. Deletion simply removes the dictionary entry, allowing garbage collection to reclaim the entire subtree.
Root protection is handled by checking for an empty component list (which only the root path produces after normalization).
Complexity
Let L be the path length and d be the depth (number of components).
Time Complexity:
mkdir,touch,read,rm: O(L) for parsing plus O(d) for traversal with hash table lookupsls: O(L + k log k) where k is the number of directory entries (for sorting)
Space Complexity: O(N + C) where N is the total number of nodes and C is the aggregate size of all file contents. Each node stores its name implicitly as a dictionary key in its parent.
from typing import List
class Node:
def __init__(self, is_file=False, content=None):
self.is_file = is_file
self.content = content
self.children = {}
def virtual_filesystem(operations, arguments):
root = Node()
results = []
def parts(path):
return [part for part in path.split('/') if part]
def find(path):
node = root
for part in parts(path):
if node.is_file or part not in node.children:
return None
node = node.children[part]
return node
for operation, args in zip(operations, arguments):
path = args[0]
names = parts(path)
if operation == 'mkdir':
if not names:
results.append(False)
continue
parent = find('/' + '/'.join(names[:-1]))
name = names[-1]
if parent is None or parent.is_file or name in parent.children:
results.append(False)
else:
parent.children[name] = Node()
results.append(True)
elif operation == 'touch':
content = args[1]
if not names:
results.append(None)
continue
parent = find('/' + '/'.join(names[:-1]))
name = names[-1]
if parent is not None and not parent.is_file:
existing = parent.children.get(name)
if existing is None:
parent.children[name] = Node(is_file=True, content=content)
elif existing.is_file:
existing.content = content
results.append(None)
elif operation == 'read':
node = find(path)
results.append(node.content if node is not None and node.is_file else None)
elif operation == 'ls':
if not names:
node = root
else:
node = find(path)
if node is None:
results.append([])
elif node.is_file:
results.append([names[-1]])
else:
results.append(sorted(node.children))
elif operation == 'rm':
if not names:
results.append(None)
continue
parent = find('/' + '/'.join(names[:-1]))
if parent is not None and not parent.is_file:
parent.children.pop(names[-1], None)
results.append(None)
else:
raise ValueError('Unknown operation')
return results