399. Evaluate Division
Asked at 20Bloomberg62Amazon50Google36Microsoft23Meta20Tower Research Capital100Urban Company89DP world88Citadel81Nuro75Uber70GE Healthcare70Snap68PhonePe64Yahoo61Rippling59TikTok53Tesla52Flipkart43Goldman Sachs28
Problem
equations[i] = [A, B] with values[i] means A / B = values[i]. For each query [C, D], return C / D, or −1.0 if it can't be determined (including any variable that never appears). The equations never contradict each other.
Example: a / b = 2.0, b / c = 3.0; queries a/c, b/a, a/e, a/a, x/x → [6.0, 0.5, -1.0, 1.0, -1.0]
a / b = 2 ⇒ edges a→b (2) and b→a (0.5). A query x / y = product of weights along any path from x to y (DFS/BFS). Unknown variable or no path → −1.
Complexity: O(Q · (V + E)).
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
g = defaultdict(dict)
for (a, b), v in zip(equations, values):
g[a][b] = v
g[b][a] = 1 / v
def dfs(x, y, seen):
if x == y:
return 1.0
seen.add(x)
for nb, w in g[x].items():
if nb not in seen:
r = dfs(nb, y, seen)
if r != -1:
return w * r
return -1.0
return [dfs(x, y, set()) if x in g and y in g else -1.0 for x, y in queries]
eq, val = [["a", "b"], ["b", "c"]], [2.0, 3.0]
qs = [["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"]]
assert Solution().calcEquation(eq, val, qs) == [6.0, 0.5, -1.0, 1.0, -1.0]
got = Solution().calcEquation([["a", "b"], ["b", "c"], ["bc", "cd"]], [1.5, 2.5, 5.0], [["a", "c"], ["c", "b"], ["bc", "cd"], ["cd", "bc"]])
assert all(abs(x - y) < 1e-5 for x, y in zip(got, [3.75, 0.4, 5.0, 0.2])) and len(got) == 4
assert Solution().calcEquation([["a", "b"]], [0.5], [["a", "b"], ["b", "a"], ["a", "c"], ["x", "y"]]) == [0.5, 2.0, -1.0, -1.0]
class Solution {
public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
Map<String, Map<String, Double>> g = new HashMap<>();
for (int i = 0; i < values.length; i++) {
String a = equations.get(i).get(0), b = equations.get(i).get(1);
g.computeIfAbsent(a, k -> new HashMap<>()).put(b, values[i]);
g.computeIfAbsent(b, k -> new HashMap<>()).put(a, 1 / values[i]);
}
double[] res = new double[queries.size()];
for (int i = 0; i < res.length; i++) {
String x = queries.get(i).get(0), y = queries.get(i).get(1);
res[i] = g.containsKey(x) && g.containsKey(y) ? dfs(g, x, y, new HashSet<>()) : -1.0;
}
return res;
}
private double dfs(Map<String, Map<String, Double>> g, String x, String y, Set<String> seen) {
if (x.equals(y)) return 1.0;
seen.add(x);
for (Map.Entry<String, Double> e : g.get(x).entrySet()) {
if (seen.contains(e.getKey())) continue;
double r = dfs(g, e.getKey(), y, seen);
if (r != -1.0) return e.getValue() * r;
}
return -1.0;
}
}
func calcEquation(equations [][]string, values []float64, queries [][]string) []float64 {
g := map[string]map[string]float64{} // a -> b -> a/b
for i, e := range equations {
a, b := e[0], e[1]
if g[a] == nil {
g[a] = map[string]float64{}
}
if g[b] == nil {
g[b] = map[string]float64{}
}
g[a][b] = values[i]
g[b][a] = 1 / values[i]
}
var dfs func(x, y string, seen map[string]bool) float64
dfs = func(x, y string, seen map[string]bool) float64 { // product of weights along a path, or -1
if x == y {
return 1
}
seen[x] = true
for nb, w := range g[x] {
if !seen[nb] {
if r := dfs(nb, y, seen); r != -1 {
return w * r
}
}
}
return -1
}
res := make([]float64, len(queries))
for i, q := range queries {
if g[q[0]] == nil || g[q[1]] == nil {
res[i] = -1
} else {
res[i] = dfs(q[0], q[1], map[string]bool{})
}
}
return res
}