Evaluate Division
Explanation & Solution
Description
You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable.
You are also given some queries, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj.
Return the answers to all queries. If a single answer cannot be determined, return -1.0.
Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
Explanation: Given: a / b = 2.0, b / c = 3.0. Queries are: a / c = (a/b) * (b/c) = 6.0, b / a = 1/(a/b) = 0.5, a / e = -1.0 (e is not defined), a / a = 1.0, x / x = -1.0 (x is not defined).
Constraints
1 <= equations.length <= 20equations[i].length == 21 <= Ai.length, Bi.length <= 5values.length == equations.length0.0 < values[i] <= 20.01 <= queries.length <= 20queries[j].length == 21 <= Cj.length, Dj.length <= 5Ai, Bi, Cj, Djconsist of lower case English letters and digits
Approach
Graphs pattern
1. Build a Weighted Graph
- Create an adjacency list using a
Map - For each equation
a / b = w, add two directed edges: a → bwith weightwb → awith weight1 / w- This captures both the forward and reverse relationships
2. Process Each Query with BFS
- For each query
[src, dst], perform a breadth-first search fromsrctodst - If either variable is not in the graph, immediately return
-1.0 - If
src === dst, return1.0(any variable divided by itself is 1)
3. Traverse and Multiply Weights
- Start BFS from
srcwith an initial product of1.0 - At each step, multiply the running product by the edge weight to the neighbor
- If we reach
dst, return the accumulated product — this is the answer - Track visited nodes to avoid cycles
4. Handle Unreachable Variables
- If BFS completes without finding
dst, the variables are in disconnected components - Return
-1.0for that query
5. Collect All Results
- Map over all queries, running BFS for each one
- Return the array of results
Key Insight
- Division relationships form a weighted graph — if
a / b = 2andb / c = 3, then the patha → b → cgivesa / c = 2 * 3 = 6 - Finding
x / yis equivalent to finding a path fromxtoyand multiplying all edge weights along that path - BFS guarantees we explore the shortest path first, and the visited set prevents infinite loops