#1166
Medium Algorithms Design file system
Hash Table String Design Trie
65.1% acceptance
Mar 31, 2026
642
81
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.
Solution
Rust
Time O(2^n)
Space O(n)
struct FileSystem {
paths: std::collections::HashMap<String, i32>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl FileSystem {
fn new() -> Self {
FileSystem {
paths: std::collections::HashMap::new(),
}
}
fn create_path(&mut self, path: String, value: i32) -> bool {
if self.paths.contains_key(&path) {
return false;
}
// Check parent exists (except for root-level paths like "/a")
if let Some(last_slash) = path.rfind('/') {
if last_slash > 0 {
let parent = &path[..last_slash];
if !self.paths.contains_key(parent) {
return false;
}
}
}
self.paths.insert(path, value);
true
}
fn get(&self, path: String) -> i32 {
*self.paths.get(&path).unwrap_or(&-1)
}
}
/*
* Your FileSystem object will be instantiated and called as such:
* let obj = FileSystem::new();
* let ret_1: bool = obj.create_path(path, value);
* let ret_2: i32 = obj.get(path);
*/