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
LeetCode-এ খুলুন ↗

আমি 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.