399. Evaluate Division

Equations are given in the formatA / B = k, whereAandBare variables represented as strings, andkis a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return-1.0.

Example: Givena / b = 2.0, b / c = 3.0. queries are:a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? . return[6.0, 0.5, -1.0, 1.0, -1.0 ].

The input is:vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries, whereequations.size() == values.size(), and the values are positive. This represents the equations. Returnvector<double>.

According to the example above:

equations = [ ["a", "b"], ["b", "c"] ],
values = [2.0, 3.0],
queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ].

The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction.

Thoughts:

  1. Explicity building adj list: for permutation of all the pairs of neighbors in one's node i , j, calculate the i , j value as q[i][k] * q[k][j]: assume q[i][i] = 1

  2. Union Find

  3. DFS

Code: Building adj list: T: O(n^3), S:(n^2)

class Solution(object):
    def calcEquation(self, equations, values, queries):
        """
        :type equations: List[List[str]]
        :type values: List[float]
        :type queries: List[List[str]]
        :rtype: List[float]
        """
        q = collections.defaultdict(dict)

        # build the graph by building the adj list
        for (a, b) , val in zip(equations, values):
            # identity
            q[a][a] = q[b][b] = 1.0
            q[a][b] = val 
            q[b][a] = 1/val

        for k in q:
            for i in q[k]:
                for j in q[k]:
                    q[i][j] = q[i][k] * q[k][j] # connecting nodes explicitly

        return [q[a].get(b, -1.0) for a , b in queries]

Code: DFS + Hash

Code: Union Find

Last updated

Was this helpful?