Design File System - Problem

You are asked to design a file system that allows you to create new paths and associate them with different values.

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

Implement the FileSystem class:

  • bool createPath(string path, int 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.
  • int get(string path) Returns the value associated with path or returns -1 if the path doesn't exist.

Input & Output

Example 1 — Basic Operations
$ Input: operations = ["FileSystem", "createPath", "get"], parameters = [[], ["/a", 1], ["/a"]]
Output: [null, true, 1]
💡 Note: Create FileSystem, create path /a with value 1, then get /a returns 1
Example 2 — Parent Path Required
$ Input: operations = ["FileSystem", "createPath", "createPath"], parameters = [[], ["/leet", 1], ["/leet/code", 2]]
Output: [null, true, true]
💡 Note: Create /leet first, then /leet/code succeeds because parent /leet exists
Example 3 — Missing Parent
$ Input: operations = ["FileSystem", "createPath"], parameters = [[], ["/leet/code", 2]]
Output: [null, false]
💡 Note: Cannot create /leet/code because parent /leet doesn't exist

Constraints

  • 1 ≤ operations.length ≤ 104
  • 1 ≤ path.length ≤ 100
  • 1 ≤ value ≤ 109

Visualization

Tap to expand
Design File System: Hierarchical Path ManagementOperations:createPath('/leet', 1)createPath('/leet/code', 2)get('/leet/code')File System Structure:/leetvalue: 1codevalue: 2Results:truetrue2Parent validation: /leet/code requires /leet to exist first✓ Hash map enables O(1) path lookups and parent checkingOutput: [null, true, true, 2]
Understanding the Visualization
1
Input Operations
Series of createPath and get operations on file paths
2
Parent Validation
Check parent path exists before creating new paths
3
Hash Map Storage
Store paths and values for fast O(1) access
Key Takeaway
🎯 Key Insight: Use hash map for O(1) path operations and extract parent paths by string manipulation for validation
Asked in
Facebook 35 Amazon 28 Google 22
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen