Problem
You are given equations of the form ai / bi = values[i], and queries of the form cj / dj. Return the answer to each query, or -1.0 when it cannot be determined from the given equations.
Original: LeetCode 399: Evaluate Division.
Examples
Example 1
`equations = [["a", "b"], ["b", "c"]], values = [2.0, 3.0], queries = [["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"]]``[6.0, 0.5, -1.0, 1.0, -1.0]`a / c = (a / b) * (b / c) = 6. Unknown variables give -1.0, even x / x.
Constraints
1 <= equations.length <= 20equations[i].length == 21 <= Ai.length, Bi.length <= 5values.length == equations.length0.0 < values[i] <= 20.01 <= queries.length <= 20queries[i].length == 21 <= Cj.length, Dj.length <= 5Ai, Bi, Cj, Djconsist of lower case English letters and digits.
Hints
Hint 1
Variables are strings. If a query mentions a variable that never appeared, or if two variables are in different connected components, the answer is -1.0. A variable divided by itself is 1.0 only when that variable is known.
Hint 2
These equations form a weighted graph. A query is a path product, so BFS, DFS, or weighted union-find works.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. For every query, search the graph from scratch. With a small number of variables this is fine.
Optimal. Build the bidirectional weighted graph once, then BFS for each query. You can also union-find with ratio-to-parent weights so each query is almost constant time after the unions.
Alternative. Floyd-Warshall over the variable set precomputes every pair if you expect many queries.
Complexity
- Time
- O(V + E)
per query, after O(E) to build the graph
- Space
- O(V + E)
Code
from collections import defaultdict, deque
def calc_equation(equations: list[list[str]], values: list[float], queries: list[list[str]]) -> list[float]:
graph = defaultdict(list)
for (a, b), v in zip(equations, values):
graph[a].append((b, v))
graph[b].append((a, 1.0 / v))
def bfs(start: str, goal: str) -> float:
if start not in graph or goal not in graph:
return -1.0
if start == goal:
return 1.0
q = deque([(start, 1.0)])
seen = {start}
while q:
node, prod = q.popleft()
if node == goal:
return prod
for nei, w in graph[node]:
if nei not in seen:
seen.add(nei)
q.append((nei, prod * w))
return -1.0
return [bfs(c, d) for c, d in queries]
if __name__ == "__main__":
ans = calc_equation(
[["a", "b"], ["b", "c"]],
[2.0, 3.0],
[["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"]],
)
assert ans == [6.0, 0.5, -1.0, 1.0, -1.0]
print("ok")import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class EvaluateDivision {
static double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
Map<String, List<Pair>> graph = new HashMap<>();
for (int i = 0; i < equations.size(); i++) {
String a = equations.get(i).get(0), b = equations.get(i).get(1);
graph.computeIfAbsent(a, k -> new ArrayList<>()).add(new Pair(b, values[i]));
graph.computeIfAbsent(b, k -> new ArrayList<>()).add(new Pair(a, 1.0 / values[i]));
}
double[] ans = new double[queries.size()];
for (int i = 0; i < queries.size(); i++) ans[i] = bfs(graph, queries.get(i).get(0), queries.get(i).get(1));
return ans;
}
static double bfs(Map<String, List<Pair>> graph, String start, String goal) {
if (!graph.containsKey(start) || !graph.containsKey(goal)) return -1.0;
if (start.equals(goal)) return 1.0;
var q = new ArrayDeque<Pair>();
var seen = new HashSet<String>();
q.add(new Pair(start, 1.0));
seen.add(start);
while (!q.isEmpty()) {
var cur = q.remove();
if (cur.node.equals(goal)) return cur.prod;
for (var e : graph.get(cur.node)) {
if (seen.add(e.node)) q.add(new Pair(e.node, cur.prod * e.prod));
}
}
return -1.0;
}
static class Pair {
String node;
double prod;
Pair(String node, double prod) { this.node = node; this.prod = prod; }
}
public static void main(String[] args) {
var eq = List.of(List.of("a", "b"), List.of("b", "c"));
var q = List.of(List.of("a", "c"), List.of("b", "a"), List.of("a", "e"), List.of("a", "a"), List.of("x", "x"));
double[] ans = calcEquation(eq, new double[] {2.0, 3.0}, q);
if (ans[0] != 6.0 || ans[1] != 0.5 || ans[2] != -1.0 || ans[3] != 1.0 || ans[4] != -1.0)
throw new AssertionError(java.util.Arrays.toString(ans));
System.out.println("ok");
}
}Edge cases
- Official sample: equations a/b = 2 and b/c = 3, with queries a/c, b/a, a/e, a/a and x/x, return 6.0, 0.5, -1.0, 1.0 and -1.0.
- x/x is -1.0 when x never appeared, not 1.0.
Follow-ups
- A weighted union-find makes each later query almost O(1) after path compression with ratio products.
Interview script
"Each equation is a directed edge with a weight, plus the reverse edge with the reciprocal. A query is the product of weights along a path, which I find with BFS. If a variable is unknown, I return -1."
Source: LeetCode 399: Evaluate Division
Sources
- LeetCode 133: Clone Graph
- LeetCode 200: Number of Islands
- LeetCode 994: Rotting Oranges
- LeetCode 547: Number of Provinces
- LeetCode 207: Course Schedule
- LeetCode 210: Course Schedule II
- LeetCode 310: Minimum Height Trees
- LeetCode 743: Network Delay Time
- Java SE 17 API: PriorityQueue
- LeetCode 399: Evaluate Division
Sources (1)
- LeetCode 399: Evaluate Divisionleetcode.com