Evaluate Division
LeetCode 399 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Weighted graph; multiply along a BFS path.
நான் Evaluate Division (LeetCode 399) ஐ இப்படித் தீர்த்தேன் — State-Space / Transformation BFS பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் 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.
நான் எப்படித் தீர்த்தேன்
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 — அடிக்கடி கேட்கப்படும் கேள்விகள்
Evaluate Division பின்னாலுள்ள 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.
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.
Evaluate Division இன் time மற்றும் space complexity என்ன?
Time: O(Q · (V + E)). Space: O(V + E). (Accepted approach: BFS with products.)
Evaluate Division இல் பொதுவான தவறுகள் என்ன?
x / x is 1 only if x appears in some equation.