Katkat

Evaluate query ratios from equations

InstacartSoftware Engineer · Technical Screen

Last updated

This problem tests your ability to model algebraic relationships as a weighted directed graph and perform pathfinding to calculate ratios between variables.

Problem Statement

You are given a list of equations equations, where each equations[i] = [A, B] represents the ratio A / B = values[i], and a list of queries queries, where each queries[j] = [C, D] asks for the result of C / D. If the result cannot be determined, return -1.0.

Each input A, B, C, D is a string representing a variable name, and values is a list of floating-point numbers. Always return the answer as a float. If a variable is not present in the equations or if there is no path between two variables, return -1.0.

Constraints

  • 1 <= equations.length <= 20
  • equations[i].length == 2
  • values.length == equations.length
  • 0.0 < values[i] <= 20.0
  • queries.length <= 20

Example

Input: equations = [["a", "b"], ["b", "c"]], values = [2.0, 3.0], queries = [["a", "c"], ["b", "a"], ["a", "e"]]

Output: [6.0, 0.5, -1.0]

Explanation:

  • a / c = (a / b) * (b / c) = 2.0 * 3.0 = 6.0
  • b / a = 1 / (a / b) = 1 / 2.0 = 0.5
  • e is unknown, so result is -1.0

Function Signature

def calcEquation(equations, values, queries):
    pass

Hints

Hint 1

Represent the variables as nodes in a graph where an edge from A to B has weight 'values[i]' and an edge from B to A has weight '1 / values[i]'.

Hint 2

For each query [C, D], use a search algorithm like Breadth-First Search (BFS) or Depth-First Search (DFS) to find a path from node C to node D.

Hint 3

During the traversal, multiply the edge weights along the path to calculate the final ratio.

Follow-up questions

  • How would you modify your approach if the equations were given as a stream of updates rather than a static list?
  • If some equations are inconsistent (e.g., a/b=2 and a/b=3), how would you detect and handle these contradictions?
  • How does the time complexity change if you use the Union-Find data structure with path compression instead of BFS/DFS?