KatInterview

Build Directory Tree Operations with Path Parsing

Data Structure DesignModel answer
MediumModel answerData Structure Designtreetriepath-parsing

Last 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 (like mkdir -p in Unix). Return True if successful or if the path already exists as a directory. Return False if 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^4 calls total to mkdir and ls

Important Cases

  • Root directory / operations
  • Paths with redundant or trailing slashes
  • Queries to non-existent locations
  • Repeated mkdir calls 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