FastPrepEvaluate Division

Evaluate Division

Bloomberg LP logoBloomberg LP● MediumNEW GRADPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

You are given variable pairs equations and positive real numbers values. For every index i, equations[i] = [a, b] and values[i] mean a / b = values[i].

For each pair in queries, return the requested quotient. Return -1.0 when it cannot be determined. The equations are valid and mutually consistent, and a variable absent from all equations is undefined even when queried against itself.

Function

calcEquation(equations: String[][], values: double[], queries: String[][]) → double[]

Examples

Example 1

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

Compose or reverse known ratios; undefined variables produce -1.0.

Example 2

equations = [["a","b"],["b","c"],["bc","cd"]]values = [1.5,2.5,5.0]queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]]return = [3.75,0.4,5.0,0.2]

Products along graph paths evaluate indirect ratios.

Example 3

equations = [["a","b"]]values = [0.5]queries = [["a","b"],["b","a"],["a","c"],["x","y"]]return = [0.5,2.0,-1.0,-1.0]

The reverse edge uses the reciprocal; unknown variables have no path.

Constraints

  • 1 <= equations.length <= 20
  • values.length == equations.length
  • 0.0 < values[i] <= 20.0
  • 1 <= queries.length <= 20
  • Variable names contain one to five lowercase letters or digits.
  • The equations contain no contradictions and no division by zero.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
    // Write your code here.
}
equations[["a","b"],["b","c"]]
values[2.0,3.0]
queries[["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
expected[6.0,0.5,-1.0,1.0,-1.0]
Checking account…