Evaluate Division

Medium Weighted graph String DFS

Problem

You are given equations of the form ai / bi = values[i], and queries of the form cj / dj. Return the answer to each query, or -1.0 when it cannot be determined from the given equations.

Original: LeetCode 399: Evaluate Division.

Examples

Example 1

Input`equations = [["a", "b"], ["b", "c"]], values = [2.0, 3.0], queries = [["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"]]`
Output`[6.0, 0.5, -1.0, 1.0, -1.0]`

a / c = (a / b) * (b / c) = 6. Unknown variables give -1.0, even x / x.

Constraints

  • 1 <= equations.length <= 20
  • equations[i].length == 2
  • 1 <= Ai.length, Bi.length <= 5
  • values.length == equations.length
  • 0.0 < values[i] <= 20.0
  • 1 <= queries.length <= 20
  • queries[i].length == 2
  • 1 <= Cj.length, Dj.length <= 5
  • Ai, Bi, Cj, Dj consist of lower case English letters and digits.

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (1)
  1. LeetCode 399: Evaluate Divisionleetcode.com