Sunday, September 11, 2016

LeetCode 399 - Evaluate Division

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

(1) Build the map, the key is dividend, the value is also a map whose key is divisor and value is its parameter. For example, a / b = 2.0, the map entry is <"a", <"b", 2.0>>. To make searching and calculation easier, we also put b / a = 0.5 into the map.
(2) for each query, use DFS to search divisors recursively

I think the key point to induct your algorithm is to find a common divisor ( the root) for the queries. Clever idea :)

We can avoid traverse the entire map by plug in children information to parent. @iambright
This my java implementation based on your idea. Further, I use weighted UnionFind with path compression in order to speed up union and find operation.