KatInterview

Compute Division Chains from Given Ratios

Trees & GraphsAuto-graded · 13 test cases
HardAuto-gradedTrees & Graphsgraphbfsunion-find

Last updated

Tests graph modeling of multiplicative relationships and pathfinding to derive transitive ratios between variables.

You receive a collection of ratio relationships and must answer queries about derived ratios.

You are given:

  • equations: a list of pairs where equations[i] = [X, Y] means you know the value of X / Y
  • values: a list of numbers where values[i] is the numeric result of equations[i][0] / equations[i][1]
  • queries: a list of pairs where queries[j] = [P, Q] asks you to compute P / Q

Return a list of answers, one per query. For each query [P, Q]:

  • If you can determine P / Q from the given equations, return that ratio as a float
  • If you cannot determine the ratio (because a variable is unknown or unreachable), return -1.0

Important rules:

  • Variables are strings
  • A variable is "known" only if it appears in at least one equation
  • For a known variable X, the ratio X / X equals 1.0
  • For an unknown variable Y, even Y / Y returns -1.0
  • All given ratios are positive and the system is consistent

Constraints

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

Examples

Example 1

Input: compute_division_queries([['a', 'b'], ['b', 'c']], [2, 3], [['a', 'c'], ['b', 'a'], ['a', 'e']])

Output: [6, 0.5, -1]

Hints

Hint 1

Model each variable as a node in a graph. What edge structure lets you compute ratios by following paths?

Hint 2

If you know A/B = k, you also know B/A = 1/k. How does this affect your graph?

Hint 3

Use BFS or DFS from the numerator. Track the accumulated product of edge weights as you traverse toward the denominator.