- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 66 lines of C++ from the credited upstream file 588.cpp.
- The implementation visibly relies on sequence storage, ordered lookup.
- 3 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct TrieNode {2 map<string, shared_ptr<TrieNode>> children; 3 bool isFile = false;4 string content;5};6 7class FileSystem {8 public:9 vector<string> ls(string path) {10 auto [node, lastDir] = createDirAndGetPair(path);11 if (node->isFile)12 return {lastDir};13 14 vector<string> ans;15 16 for (const auto& [file, _] : node->children)17 ans.push_back(file);18 19 return ans;20 }21 22 void mkdir(string path) {23 createDirAndGetPair(path);24 }25 26 void addContentToFile(string filePath, string content) {27 shared_ptr<TrieNode> node = createDirAndGetPair(filePath).first;28 node->isFile = true;29 node->content += content;30 }31 32 string readContentFromFile(string filePath) {33 shared_ptr<TrieNode> node = createDirAndGetPair(filePath).first;34 return node->content;35 }36 37 private:38 shared_ptr<TrieNode> root = make_shared<TrieNode>();39 40 41 pair<shared_ptr<TrieNode>, string> createDirAndGetPair(const string& path) {42 const vector<string> dirs = getDirs(path);43 shared_ptr<TrieNode> node = root;44 45 for (const string& dir : dirs) {46 if (!node->children.contains(dir))47 node->children[dir] = make_shared<TrieNode>();48 node = node->children[dir];49 }50 51 return {node, dirs.empty() ? "" : dirs.back()};52 }53 54 55 vector<string> getDirs(const string& path) {56 vector<string> dirs;57 istringstream iss(path);58 59 for (string dir; getline(iss, dir, '/');)60 if (!dir.empty()) 61 dirs.push_back(dir);62 63 return dirs;64 }65};66