- 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
- 51 lines of C++ from the credited upstream file 399.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.
1class Solution {2 public:3 vector<double> calcEquation(vector<vector<string>>& equations,4 vector<double>& values,5 vector<vector<string>>& queries) {6 vector<double> ans;7 8 unordered_map<string, unordered_map<string, double>> graph;9 10 for (int i = 0; i < equations.size(); ++i) {11 const string& A = equations[i][0];12 const string& B = equations[i][1];13 graph[A][B] = values[i];14 graph[B][A] = 1 / values[i];15 }16 17 for (const vector<string>& query : queries) {18 const string& A = query[0];19 const string& C = query[1];20 if (!graph.contains(A) || !graph.contains(C))21 ans.push_back(-1);22 else23 ans.push_back(divide(graph, A, C, unordered_set<string>()));24 }25 26 return ans;27 }28 29 private:30 31 double divide(32 const unordered_map<string, unordered_map<string, double>>& graph,33 const string& A, const string& C, unordered_set<string>&& seen) {34 if (A == C)35 return 1.0;36 37 seen.insert(A);38 39 40 for (const auto& [B, value] : graph.at(A)) {41 if (seen.contains(B))42 continue;43 const double res = divide(graph, B, C, std::move(seen)); 44 if (res > 0) 45 return value * res; 46 }47 48 return -1; 49 }50};51