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 INPUT Operations: 1. FileSystem() 2. createPath("/a", 1) 3. get("/a") Path Structure: / a val: 1 ALGORITHM STEPS 1 Initialize HashMap Store path-value pairs 2 createPath Logic Check parent exists 3 Add to HashMap map["/a"] = 1 4 get() Lookup Return map[path] HashMap State: Key: "/" --> Val: (root) Key: "/a" --> Val: 1 Time: O(1) lookup | Space: O(n) FINAL RESULT Execution Trace: FileSystem() Returns: null (init OK) createPath("/a", 1) Returns: true (success) get("/a") Returns: 1 (value found) Output Array: [null, true, 1] All Operations Completed OK Key Insight: HashMap provides O(1) path lookup and creation. For createPath, we validate that the parent path exists (except for root children) and the path doesn't already exist. This ensures valid hierarchical structure while maintaining constant-time operations for both read and write. TutorialsPoint - Design File System | Hash Map Optimization
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