Solve LeetCode 399: Evaluate Division in Python with a weighted graph search approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.
This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Graph General |
| Reusable pattern | weighted graph search |
| Complexity | O((V+E) per query) time and O(V+E) space |
What the problem is testing
Represent each equation as two reciprocal weighted edges. For a query, search for a path and multiply weights along it.
Algorithm
- Represent each equation as two reciprocal weighted edges. For a query, search for a path and multiply weights along it.
- Maintain this invariant: The accumulated product equals the ratio from the query source to the current graph node.
- Continue until every input item or reachable state has been resolved, then return the accumulated result.
Python solution
from collections import Counter, defaultdict, deque, OrderedDict
import random
class Solution:
def calcEquation(self, equations, values, queries):
graph = defaultdict(list)
for (a, b), value in zip(equations, values):
graph[a].append((b, value)); graph[b].append((a, 1.0 / value))
def search(start, end):
if start not in graph or end not in graph: return -1.0
stack, seen = [(start, 1.0)], {start}
while stack:
node, product = stack.pop()
if node == end: return product
for neighbor, weight in graph[node]:
if neighbor not in seen:
seen.add(neighbor); stack.append((neighbor, product * weight))
return -1.0
return [search(a, b) for a, b in queries]Why this is correct
The proof follows the maintained state: The accumulated product equals the ratio from the query source to the current graph node. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.
Complexity
O((V+E) per query) time and O(V+E) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.
Edge cases
Unknown variables and disconnected pairs return -1; a known variable divided by itself is one.
Tested reference code
This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 133. Clone Graph · Next: 207. Course Schedule