Build an In-Memory Hierarchical File System with CRUD Support
Data Structure DesignModel answerLast updated
Design and implement an in-memory key-value store structured as a file system tree supporting create, set, get, and cascade delete operations with path validation.
Design an in-memory hierarchical file system that maps unique string paths to integer values. Your system should store values at specific path nodes and enforce hierarchical structural rules.
Implement the FileSystem class with the following methods:
create(path: str, value: int) -> bool: Creates a new path node containingvalue. Returnstrueif creation is successful. Returnsfalseif the path format is invalid, if the path already exists, or if its parent path does not exist. (The root directory/exists implicitly at initialization and cannot be explicitly created).get(path: str) -> int: Returns the integer value associated withpath. If the path does not exist or is invalid, returns-1.set(path: str, value: int) -> bool: Updates the integer value at an existingpath. Returnstrueif successful. Returnsfalseif the path does not exist or is invalid (does not create non-existent nodes).delete(path: str) -> bool: Removes the specifiedpathand all of its descendants (a recursive directory removal). Returnstrueif the path existed and was successfully deleted. Returnsfalseif the path does not exist or is invalid.
Path Formatting Rules
A path is considered valid if and only if:
- It begins with a single forward slash
/. - It is not equal to
/itself (the root directory cannot be modified, assigned a value, or deleted). - It contains no trailing slashes (e.g.,
/foo/is invalid). - It contains no consecutive slashes (e.g.,
/foo//baris invalid). - Each directory/file name segment consists solely of lowercase English letters (
a-z).
Examples
fs = FileSystem()
# Step 1: Create top-level path
fs.create("/user", 10) # returns True
# Step 2: Create nested path under existing parent
fs.create("/user/profile", 20) # returns True
# Step 3: Attempting to create under non-existent parent fails
fs.create("/admin/settings", 30) # returns False (parent "/admin" does not exist)
# Step 4: Duplicate path creation fails
fs.create("/user", 15) # returns False
# Step 5: Fetch values
fs.get("/user/profile") # returns 20
fs.get("/missing") # returns -1
# Step 6: Update existing value
fs.set("/user/profile", 25) # returns True
fs.get("/user/profile") # returns 25
# Step 7: Cascading delete
fs.delete("/user") # returns True (deletes "/user" and "/user/profile")
fs.get("/user/profile") # returns -1
Hints
Hint 1
Consider representing the file system as a segment-based Trie (prefix tree) rather than a flat hash map.
Hint 2
Think about how `delete` behaves in a Trie versus a flat Hash Map: unlinking a single child pointer in a Trie automatically disconnects all descendant nodes in O(depth) time.
Hint 3
Ensure strict validation of path strings before performing structural lookups or operations to prevent partial or invalid state updates.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
To build an efficient in-memory hierarchical file system, we can evaluate two main data structure choices:
-
Flat Hash Map (
dict[str, int]):create,get, andsettake $O(L)$ time, where $L$ is the path string length. We simply validate the path and split it to check ifparent_pathexists in the map.- However,
delete(path)becomes inefficient. Removing a path along with all its nested descendants requires scanning all keys in the hash map to find those starting withpath + "/". This leads to $O(N \cdot L)$ time, where $N$ is the total number of paths.
-
Prefix Tree / Trie Node Structure:
- Each node in the tree contains a dictionary of
childrenmapping a segment name (e.g.,"user") to its corresponding childNode, along with an optional storedvalue. create,get, andsetnavigate down the tree segment by segment in $O(L)$ time.delete(path)locates the parent node of the target segment and removes the segment key from the parent'schildrenhash table. Detaching this single reference drops the entire subtree in $O(L)$ time, leaving garbage collection to clean up the orphaned nodes.
- Each node in the tree contains a dictionary of
Because cascading deletions are required, a Segment Trie is the optimal structure.
Python 3 Implementation
from typing import Dict, List, Optional
class TrieNode:
__slots__ = ("children", "value")
def __init__(self, value: Optional[int] = None) -> None:
self.children: Dict[str, "TrieNode"] = {}
self.value: Optional[int] = value
class FileSystem:
NOT_FOUND = -1
def __init__(self) -> None:
# Root node represents "/" and holds no direct value
self._root = TrieNode()
def _parse_and_validate(self, path: str) -> Optional[List[str]]:
"""Validates path string and returns path segments if valid, else None."""
if not isinstance(path, str) or not path.startswith("/") or path == "/":
return None
# Ignore initial '/' by slicing from index 1
segments = path[1:].split("/")
for seg in segments:
if not seg or not seg.isalpha() or not seg.islower():
return None
return segments
def _find_node(self, segments: List[str]) -> Optional[TrieNode]:
"""Traverses the Trie along path segments and returns the final node."""
curr = self._root
for seg in segments:
if seg not in curr.children:
return None
curr = curr.children[seg]
return curr
def create(self, path: str, value: int) -> bool:
segments = self._parse_and_validate(path)
if segments is None:
return False
# Find parent node (all segments except the last one)
parent_segments = segments[:-1]
target_name = segments[-1]
parent_node = self._find_node(parent_segments)
# Parent must exist, and target segment must not already exist
if parent_node is None or target_name in parent_node.children:
return False
parent_node.children[target_name] = TrieNode(value)
return True
def get(self, path: str) -> int:
segments = self._parse_and_validate(path)
if segments is None:
return self.NOT_FOUND
node = self._find_node(segments)
return node.value if node is not None and node.value is not None else self.NOT_FOUND
def set(self, path: str, value: int) -> bool:
segments = self._parse_and_validate(path)
if segments is None:
return False
node = self._find_node(segments)
if node is None:
return False
node.value = value
return True
def delete(self, path: str) -> bool:
segments = self._parse_and_validate(path)
if segments is None:
return False
parent_segments = segments[:-1]
target_name = segments[-1]
parent_node = self._find_node(parent_segments)
if parent_node is None or target_name not in parent_node.children:
return False
# Unlink target node and all its descendants
del parent_node.children[target_name]
return True
Complexity Analysis
-
Time Complexity:
create(path, value): $\mathcal{O}(L)$, where $L$ is the character length of the path string. Parsing and navigating through segments both take time proportional to $L$.get(path): $\mathcal{O}(L)$ to split the string and step through hash maps.set(path, value): $\mathcal{O}(L)$ to locate the node and update its value.delete(path): $\mathcal{O}(L)$ to locate the parent node and remove the child key reference.
-
Space Complexity:
- $\mathcal{O}(S \cdot K)$ total space, where $S$ is the total number of unique paths added and $K$ is the average segment length. Each path segment creates one
TrieNode.
- $\mathcal{O}(S \cdot K)$ total space, where $S$ is the total number of unique paths added and $K$ is the average segment length. Each path segment creates one