Design File System
Core idea: A path like
/leet/codeis not a string — it's a sequence of components["leet", "code"]. Store those components in a trie where each edge is one component name (not one character), and the structure itself encodes the parent/child relationship thatcreatePathhas to validate.
Problem, rephrased
Imagine you're building the directory layer of a tiny in-memory virtual file system. People hand you absolute paths — strings of the form / followed by one or more lowercase-letter segments, e.g. /leetcode or /leetcode/problems — and ask you to remember a value at each path. You support exactly two operations:
createPath(path, value)— create the path and attachvalueto it. ReturnTrueon success. ReturnFalseif the path already exists, or if its parent path doesn't exist yet. (You can't create/a/buntil/ais already there.)get(path)— return the value stored atpath, or-1if no such path exists.
The empty string "" and the bare "/" are not valid paths.
| Operation | Result | Why |
|---|---|---|
createPath("/a", 1) |
True |
parent is the root (always exists); /a is new |
createPath("/a/b", 2) |
True |
parent /a exists; /a/b is new |
createPath("/c/d", 1) |
False |
parent /c doesn't exist |
createPath("/a", 9) |
False |
/a already exists |
get("/a/b") |
2 |
value stored there |
get("/c") |
-1 |
never created |
This is LeetCode 1166 — Design File System.
Sign in to continue reading
The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.
Sign in to read the full lesson