- 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 Java from the credited upstream file 399.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered 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 double[] calcEquation(List<List<String>> equations, double[] values,3 List<List<String>> queries) {4 double[] ans = new double[queries.size()];5 6 Map<String, Map<String, Double>> graph = new HashMap<>();7 8 9 for (int i = 0; i < equations.size(); ++i) {10 final String A = equations.get(i).get(0);11 final String B = equations.get(i).get(1);12 graph.putIfAbsent(A, new HashMap<>());13 graph.putIfAbsent(B, new HashMap<>());14 graph.get(A).put(B, values[i]);15 graph.get(B).put(A, 1.0 / values[i]);16 }17 18 for (int i = 0; i < queries.size(); ++i) {19 final String A = queries.get(i).get(0);20 final String C = queries.get(i).get(1);21 if (!graph.containsKey(A) || !graph.containsKey(C))22 ans[i] = -1.0;23 else24 ans[i] = divide(graph, A, C, new HashSet<>());25 }26 27 return ans;28 }29 30 31 private double divide(Map<String, Map<String, Double>> graph, final String A, final String C,32 Set<String> seen) {33 if (A.equals(C))34 return 1.0;35 36 seen.add(A);37 38 for (final String B : graph.get(A).keySet()) {39 if (seen.contains(B))40 continue;41 final double res = divide(graph, B, C, seen); 42 if (res > 0) 43 return graph.get(A).get(B) * res; 44 }45 46 return -1.0; 47 }48}49