Build Directory Tree Operations with Path Parsing
Data Structure DesignModel answerLast updated
Implement directory creation and listing for an in-memory hierarchical structure with automatic parent creation and path normalization.
Problem Statement
Build an in-memory hierarchical directory structure that supports two core operations: creating directory paths and listing directory contents.
Your implementation should provide a FileSystem class with these methods:
FileSystem(): Initialize an empty structure with a root directory/mkdir(path: str) -> bool: Create all directories along the given absolute path. Parent directories are created automatically when missing (likemkdir -pin Unix). ReturnTrueif successful or if the path already exists as a directory. ReturnFalseif creation fails due to invalid format or conflicts.ls(path: str) -> list[str]: Return the names of all immediate children within the specified directory, in alphabetical order. Return an empty list if the path doesn't exist or isn't a directory.
Path Requirements
- All paths must be absolute, starting with
/ - Directory names contain only lowercase letters and digits (
a-z,0-9) - Multiple consecutive slashes (like
//a///b) are treated as single separators - Trailing slashes are ignored (so
/a/b/equals/a/b)
Examples
fs = FileSystem()
# Initially empty root
fs.ls("/") # returns []
# Build nested structure
fs.mkdir("/company/engineering") # returns True
fs.mkdir("/company/sales") # returns True
# List children
fs.ls("/company") # returns ["engineering", "sales"]
fs.ls("/") # returns ["company"]
# Path normalization
fs.mkdir("//company///marketing/") # returns True
fs.ls("/company/") # returns ["engineering", "marketing", "sales"]
# Non-existent path
fs.ls("/missing") # returns []
Constraints
1 <= path.length <= 500- Directory names: lowercase letters and digits only
- At most
10^4calls total tomkdirandls
Important Cases
- Root directory
/operations - Paths with redundant or trailing slashes
- Queries to non-existent locations
- Repeated
mkdircalls on existing paths
Hints
Hint 1
Think of the directory structure as a tree where each node maps child names to child nodes
Hint 2
Parse paths by splitting on '/' and filtering out empty segments to handle multiple slashes
Hint 3
Consider using a hash map at each node to store children, making lookup and insertion efficient
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
The core insight is to represent the directory hierarchy as a tree of nodes, where each node maintains a mapping from child names to child node objects. This structure is similar to a trie but operates on path segments rather than individual characters.
Data Structure Design
Create a Node class with:
- A dictionary mapping child names to child
Nodeobjects - A boolean flag indicating whether this node represents a directory (useful for future extensions with files)
The FileSystem maintains a root node representing /.
Path Processing Strategy
Every operation begins by transforming the raw path string into a normalized list of components:
- Validation: Ensure the path starts with
/ - Splitting: Divide the path on
/delimiters - Filtering: Remove empty strings (this automatically handles
//a///b→['a', 'b']and trailing slashes) - Component validation: Verify each segment contains only lowercase letters and digits
The root path / normalizes to an empty list [], which correctly represents "no components to traverse."
Implementation Logic
For mkdir(path):
- Parse and validate the path
- Walk the tree from root, component by component
- When a child doesn't exist, create a new directory node
- When a child exists but isn't a directory, fail immediately
- Return
Trueon success or if the path already exists
For ls(path):
- Parse and validate the path
- Walk the tree to find the target node
- If any component is missing or isn't a directory, return
[] - Otherwise, return the sorted list of child names
Why This Works
Correctness of normalization: Splitting "//uber///freight/" on / produces ['', '', 'uber', '', '', 'freight', '']. After filtering empty strings, we get ['uber', 'freight'], the canonical form.
Parent creation semantics: By creating missing nodes during traversal, we guarantee all prefixes of the path exist as directories after mkdir completes.
Idempotency: mkdir on an existing directory simply walks to it and returns True, making the operation safe to repeat.
Failure atomicity: Conflicts are detected during traversal through existing nodes. Once we create a new node, all descendants are new too, so no conflicts can occur beyond that point. Invalid paths are caught before any modifications occur.
Complexity Analysis
Let L = path length and k = number of children in the listed directory.
mkdir: O(L) — parsing takes O(L), and each component requires one dictionary lookup or insertionls: O(L + k log k) — O(L) to walk the path, then O(k log k) to sort the children- Space: O(total characters stored across all directory names) + O(L) temporary space for parsed components
Trade-offs
Using an unsorted dictionary for children keeps insertions O(1) and pays the sorting cost only when listing. This is optimal when writes outnumber reads. If listing became the dominant operation, storing children in a balanced tree would make ls O(L + k) at the cost of O(log k) insertions.
Edge Cases Handled
ls("/")on a fresh system →[](root has no children yet)mkdir("/")→True(root already exists)mkdir("/a/b")thenmkdir("/a")→ both returnTrue(idempotent)- Invalid paths like
"relative/path"or"/PATH/With/Caps"→Falsefrommkdir,[]fromls ls("/does/not/exist")→[]
Python Implementation
from typing import Dict, List, Optional
class Node:
def __init__(self, is_dir: bool = True):
self.children: Dict[str, Node] = {}
self.is_dir = is_dir
def is_valid_name(name: str) -> bool:
"""Check if a component contains only lowercase letters and digits."""
return bool(name) and all(c.islower() or c.isdigit() for c in name)
class FileSystem:
def __init__(self):
self.root = Node(is_dir=True)
def _normalize_path(self, path: str) -> Optional[List[str]]:
"""Parse path into components, return None if invalid."""
if not path or not path.startswith("/"):
return None
components = [part for part in path.split("/") if part]
if not all(is_valid_name(comp) for comp in components):
return None
return components
def mkdir(self, path: str) -> bool:
components = self._normalize_path(path)
if components is None:
return False
current = self.root
for name in components:
if name not in current.children:
current.children[name] = Node(is_dir=True)
elif not current.children[name].is_dir:
return False # conflict: component exists but isn't a directory
current = current.children[name]
return True
def ls(self, path: str) -> List[str]:
components = self._normalize_path(path)
if components is None:
return []
current = self.root
for name in components:
if name not in current.children or not current.children[name].is_dir:
return []
current = current.children[name]
return sorted(current.children.keys())
Common Mistakes
- Not handling multiple slashes: Forgetting to filter empty strings after splitting leaves ghost components
- Mutating state on validation failure: Running validation after starting to create nodes can leave partial state
- Forgetting root edge case: Special-casing
/instead of letting it normalize to[]adds unnecessary complexity - Inefficient sorting: Keeping children pre-sorted with O(log k) inserts when writes are common
Extension: Adding Files
To support file operations:
- Add a
contentfield toNodeand useis_dir=Falsefor files create_file(path, content)walks to the parent (creating it or requiring it exists), then adds a file node- Fail if any intermediate component is a file, or if the target already exists as a directory
read_file(path)walks to the node and returns its content, failing if missing or a directory- Decide whether
lson a file returns[]or[filename]based on requirements