Design File System in Python

A file system data structure allows us to create paths and associate values with them. We need to implement two main operations: creating a path with a value and retrieving the value associated with a path.

Problem Requirements

We need to design a file system that provides these two functions:

  • createPath(path, value) − Creates a new path and associates a value to it if possible and returns True. Returns False if the path already exists or its parent path doesn't exist.
  • get(path) − Finds the value associated with a path or returns -1 if the path doesn't exist.

The format of a path is one or more concatenated strings of the form: forward slash / followed by one or more lowercase English letters. For example, /programming and /programming/problems are valid paths while an empty string and / are not.

Implementation Approach

We'll use a nested dictionary structure where each path component maps to a list containing [value, children_dict]. This allows us to store both the value and maintain the hierarchical structure.

Complete Implementation

class FileSystem:
    def __init__(self):
        """Initialize the file system with an empty dictionary."""
        self.root = {}
    
    def createPath(self, path, value):
        """
        Create a new path with associated value.
        Returns True if successful, False otherwise.
        """
        # Split path into components, removing empty strings
        components = [comp for comp in path.split('/') if comp]
        
        current = self.root
        
        # Navigate to parent directory, check if all parents exist
        for i in range(len(components) - 1):
            component = components[i]
            if component not in current:
                return False  # Parent path doesn't exist
            current = current[component][1]  # Move to children dict
        
        # Check if the final component already exists
        final_component = components[-1]
        if final_component in current:
            return False  # Path already exists
        
        # Create the new path with value and empty children dict
        current[final_component] = [value, {}]
        return True
    
    def get(self, path):
        """
        Get the value associated with a path.
        Returns the value if found, -1 otherwise.
        """
        # Split path into components, removing empty strings
        components = [comp for comp in path.split('/') if comp]
        
        current = self.root
        
        # Navigate through all components except the last
        for i in range(len(components) - 1):
            component = components[i]
            if component not in current:
                return -1  # Path doesn't exist
            current = current[component][1]  # Move to children dict
        
        # Check if final component exists and return its value
        final_component = components[-1]
        if final_component in current:
            return current[final_component][0]  # Return the value
        else:
            return -1  # Path doesn't exist

# Example usage
fs = FileSystem()

# Create some paths
print("Creating /a with value 1:", fs.createPath("/a", 1))
print("Creating /a/b with value 2:", fs.createPath("/a/b", 2))
print("Creating /c without parent:", fs.createPath("/c/d", 3))
print("Creating /a again:", fs.createPath("/a", 4))

# Get values
print("Getting /a:", fs.get("/a"))
print("Getting /a/b:", fs.get("/a/b"))
print("Getting non-existent path:", fs.get("/x"))
Creating /a with value 1: True
Creating /a/b with value 2: True
Creating /c without parent: False
Creating /a again: False
Getting /a: 1
Getting /a/b: 2
Getting non-existent path: -1

How It Works

The file system uses a nested dictionary structure:

  • Each path component maps to a list: [value, children_dictionary]
  • The createPath method splits the path, verifies all parent directories exist, and creates the new path if valid
  • The get method navigates through the path components and returns the associated value

Key Features

  • Hierarchical Structure − Maintains parent-child relationships between paths
  • Path Validation − Ensures parent paths exist before creating children
  • Duplicate Prevention − Prevents overwriting existing paths
  • Efficient Lookup − O(d) time complexity where d is the depth of the path

Conclusion

This file system implementation uses nested dictionaries to maintain hierarchical path structure efficiently. The design ensures path integrity by validating parent paths exist before creating children and prevents duplicate path creation.

Updated on: 2026-03-25T08:24:42+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements