Tensorum
YouTubeसीखना शुरू करें
LeetCode 399 · State-Space / Transformation BFS

Evaluate Division

LeetCode 399 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

Weighted graph; multiply along a BFS path.

मध्यमArrayStringDepth-First SearchBreadth-First SearchUnion-Find

मैंने 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. 1

    Add both directions for every equation.

  2. 2

    For each query, BFS from x multiplying weights.

  3. 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.