- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 49 lines of C++ from the credited upstream file 1166.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 3 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
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 unordered_map<string, shared_ptr<TrieNode>> children;3 int value;4 TrieNode(int value) : value(value) {}5};6 7class FileSystem {8 public:9 bool createPath(string path, int value) {10 const vector<string> subpaths = getSubpaths(path);11 shared_ptr<TrieNode> node = root;12 13 for (int i = 0; i < subpaths.size() - 1; ++i) {14 auto it = node->children.find(subpaths[i]);15 if (it == node->children.end())16 return false;17 node = it->second;18 }19 20 if (node->children.contains(subpaths.back()))21 return false;22 node->children[subpaths.back()] = make_shared<TrieNode>(value);23 return true;24 }25 26 int get(string path) {27 shared_ptr<TrieNode> node = root;28 for (const string& subpath : getSubpaths(path)) {29 auto it = node->children.find(subpath);30 if (it == node->children.end())31 return -1;32 node = it->second;33 }34 return node->value;35 }36 37 private:38 shared_ptr<TrieNode> root = make_shared<TrieNode>(0);39 40 vector<string> getSubpaths(const string& path) {41 vector<string> subpaths;42 istringstream iss(path);43 for (string subpath; getline(iss, subpath, '/');)44 if (!subpath.empty())45 subpaths.push_back(subpath);46 return subpaths;47 }48};49