LeetCode 1166: Design File System Solution

Master LeetCode problem 1166 (Design File System), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1166. Design File System

Problem Explanation

Explanation:

To design a file system, we can use a trie data structure where each node represents a directory and contains a hashmap to store subdirectories or files. We will maintain a root node representing the root directory ("/").

Algorithm:

  1. Implement a TrieNode class to represent each directory in the file system.
  2. Implement a Filesystem class that contains a root TrieNode and methods to create directories and files.
  3. Implement createPath method to create a path in the file system.
  4. Traverse the path and create directories as needed.
  5. Return true if the path is successfully created, false if any part of the path already exists as a file.

Time Complexity:

  • The time complexity for creating a path is O(n), where n is the length of the path.

Space Complexity:

  • The space complexity is O(m), where m is the total number of directories and files created.

:

Solution Code

class TrieNode {
    Map<String, TrieNode> children;
    
    public TrieNode() {
        children = new HashMap<>();
    }
}

class FileSystem {
    TrieNode root;
    
    public FileSystem() {
        root = new TrieNode();
    }
    
    public boolean createPath(String path, int value) {
        String[] dirs = path.split("/");
        TrieNode curr = root;
        for (int i = 1; i < dirs.length - 1; i++) {
            if (!curr.children.containsKey(dirs[i])) {
                curr.children.put(dirs[i], new TrieNode());
            }
            curr = curr.children.get(dirs[i]);
        }
        if (curr.children.containsKey(dirs[dirs.length - 1])) {
            return false;
        }
        curr.children.put(dirs[dirs.length - 1], new TrieNode());
        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1166 (Design File System)?

This page provides optimized solutions for LeetCode problem 1166 (Design File System) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1166 (Design File System)?

The time complexity for LeetCode 1166 (Design File System) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1166 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1166 in Java, C++, or Python.

Back to LeetCode Solutions