Skip to content

Evaluate Division

You are given an array of variable pairs equations where equations[i] = [ai, bi] and an array of real numbers values where values[i] represents the value of ai / bi. You are also given some queries where queries[j] = [cj, dj].

For each query, calculate the value of cj / dj and return the answer. If a single answer cannot be determined, return -1.0.

equationsvaluesqueriesOutputExplanation
[["a","b"],["b","c"]][2.0,3.0][["a","c"],["b","a"],["a","e"]][6.0,0.5,-1.0]a/b=2, b/c=3 → a/c=6. b/a=0.5. a/e=-1 (not connected)
[["a","b"]][0.5][["a","b"],["b","a"],["c","c"]][0.5,2.0,1.0]a/b=0.5, b/a=2, c/c=1
[["x1","x2"],["x2","x3"]][2.0,3.0][["x1","x3"],["x3","x1"]][6.0,0.166...]x1/x3=6, x3/x1≈0.167
  • 1 <= equations.length <= 20
  • equations[i].length == 2
  • 1 <= queries.length <= 20
  • queries[i].length == 2
  • 1 <= len(equations[i][j]) <= 5
  • -100.0 < values[i] <= 100.0
  • All equations are unique, answers are at most 10^5 in absolute value
ApproachTimeSpaceNotes
DFSO(n)O(n)First approach
Union-FindO(n)O(n)Second approach
★ Recommended
⏱ Time O(n) 💾 Space O(n)
evaluate_division_dfs.py
def calcEquation(equations, values, queries):
graph = {}
for (a, b), val in zip(equations, values):
if a not in graph:
graph[a] = []
if b not in graph:
graph[b] = []
graph[a].append((b, val))
graph[b].append((a, 1.0 / val))
def dfs(start, end, visited):
if start not in graph or end not in graph:
return -1.0
if start == end:
return 1.0
visited.add(start)
for neighbor, weight in graph[start]:
if neighbor not in visited:
result = dfs(neighbor, end, visited)
if result != -1.0:
return result * weight
return -1.0
return [dfs(a, b, set()) for a, b in queries]
✓ Simple
⏱ Time O(n) 💾 Space O(n)
evaluate_division_union-find.py
def calcEquation(equations, values, queries):
parent = {}
rank = {}
def find(x):
if x not in parent:
parent[x] = x
rank[x] = 0
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
def union(a, b, val):
pa, pb = find(a), find(b)
if pa == pb:
return
parent[pb] = pa
rank[pa] = max(rank[pa], rank[pb] + 1)
for (a, b), val in zip(equations, values):
union(a, b, val)
result = []
for x, y in queries:
if find(x) != find(y):
result.append(-1.0)
else:
result.append(1.0)
return result