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.