Statementâ–¼
We are given three arrays:
equations
: Here, eachequations[i]
represents a pair of variables[a[i], b[i]]
, where eachÂa[i]
 orÂb[i]
 is a string that represents a single variable.values
: This array contains real numbers that are the result values when the first variable inequations[i]
is divided by the second. For example, ifequations[i] = ["m", "n"]
andvalues[i] = 2.0
, it means thatm / n = 2.0
.queries
: Here, eachqueries[i]
represents a pair of variables[c[i], d[i]]
, where eachÂc[i]
 orÂd[i]
 is a string that represents a single variable. The answer to each query must be calculated asÂc[i] / d[i]
.
Given these arrays, find the result of each queries[i]
by dividing the first variable with the second. To answer all the queries correctly, use the given equations
and values
. If it's impossible to determine the answer to any query based on the given equations and values, return
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.
Constraints:
1≤ equations.length
≤20 equations[i].length
==2 1≤ a[i].length
,b[i].length
≤5 values.length
== equations.length
0.0< values[i]
≤20.0 1≤ queries.length
≤20 queries[i].length
==2 1≤ c[j].length
,d[j].length
≤5 a[i], b[i], c[j], d[j]
consist of lower case English letters and digits.
Solution
Dealing with three arrays as input—equations
, values
, and queries
—can make this problem seem complex. However, a better approach is by visualizing the problem as a graph. In this graph, the variables in equations
act as nodes, and the division relationships between them are the directed edges that connect these nodes. The edges are weighted with the division results as per values
.
By considering the variables as interconnected nodes and the division operations as the links between them, we can more easily understand how to navigate from one variable to another to solve the queries. Let’s look at the following visualization that simplifies the process of finding the division results for each query.