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.