Evaluate Division
LeetCode 399 · Medium · solution, intuition & step-by-step walkthrough
Weighted graph; multiply along a BFS path.
This is how I solved Evaluate Division (LeetCode 399), a medium problem from the State-Space / Transformation BFS pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Each equation a / b = k is a weighted edge a → b with weight k (and b → a with 1/k). A query x / y is the product of weights along any path from x to y.
Approach
- 1
Add both directions for every equation.
- 2
For each query, BFS from x multiplying weights.
- 3
Unknown variable or unreachable → −1.
How I solved it
BFS with productsPythonO(Q·(V+E)) time
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
#a->b : 2, b->c:3
#a->c: 2*3
adj = defaultdict(list)
for i,pair in enumerate(equations):
u,v = pair
adj[u].append((v,values[i]))
adj[v].append((u,(1/values[i])))
def bfs(start,end):
if start not in adj or end not in adj:
return -1.0
q = deque([(start,1.0)])
visited = set()
visited.add(start)
while q:
node,wt = q.popleft()
if node==end:
return wt
for adj_node,w in adj[node]:
if adj_node not in visited:
visited.add(adj_node)
q.append((adj_node,w*wt))
return -1.0
res=[]
for u,v in queries:
res.append(bfs(u,v))
return res
Evaluate Division — FAQ
What is the intuition behind Evaluate Division?
Each equation a / b = k is a weighted edge a → b with weight k (and b → a with 1/k). A query x / y is the product of weights along any path from x to y.
How do you solve Evaluate Division (LeetCode 399)?
1. Add both directions for every equation. 2. For each query, BFS from x multiplying weights. 3. Unknown variable or unreachable → −1.
What is the time and space complexity of Evaluate Division?
Time: O(Q · (V + E)). Space: O(V + E). (Accepted approach: BFS with products.)
What are common mistakes in Evaluate Division?
x / x is 1 only if x appears in some equation.