You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable.
You are also given some queries, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj = ?.
Return the answers to all queries. If a single answer cannot be determined, return -1.0.
Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
Note: The variables that do not occur in the list of equations are undefined, so the answer cannot be determined for them.
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.00000,0.50000,-1.00000,1.00000,-1.00000] Explanation: Given: a / b = 2.0, b / c = 3.0 queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? return: [6.0, 0.5, -1.0, 1.0, -1.0 ] note: x is undefined => -1.0
Example 2:
Input: equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]] Output: [3.75000,0.40000,5.00000,0.20000]
Example 3:
Input: equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]] Output: [0.50000,2.00000,-1.00000,-1.00000]
Constraints:
1 <= equations.length <= 20equations[i].length == 21 <= Ai.length, Bi.length <= 5values.length == equations.length0.0 < values[i] <= 20.01 <= queries.length <= 20queries[i].length == 21 <= Cj.length, Dj.length <= 5Ai, Bi, Cj, Dj consist of lower case English letters and digits.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are given a giant web of clues where certain items are connected to others by multiplication and division multipliers. The brute force approach tries to explore every single chain of connections blindly from the starting item to see if you can eventually reach the target item.
Here's how the algorithm would work step-by-step:
def calc_equation(equations, values, queries):
adjacency_list = {}
for equation_index, (numerator, denominator) in enumerate(equations):
multiplier = values[equation_index]
if numerator not in adjacency_list:
adjacency_list[numerator] = {}
adjacency_list[numerator][denominator] = multiplier
if denominator not in adjacency_list:
adjacency_list[denominator] = {}
adjacency_list[denominator][numerator] = 1.0 / multiplier
def explore_paths(current_node, target_node, accumulated_product, visited_nodes):
# Check direct neighbours first to see if we reached the target immediately
if current_node == target_node:
return accumulated_product
visited_nodes.add(current_node)
for neighbor_node, edge_weight in adjacency_list[current_node].items():
if neighbor_node not in visited_nodes:
# Recursively follow this path multiplying weights along the way
result = explore_paths(neighbor_node, target_node, accumulated_product * edge_weight, visited_nodes)
if result != -1.0:
return result
# Remove node from visited set so other independent paths can use it
visited_nodes.remove(current_node)
return -1.0
final_answers = []
for query_numerator, query_denominator in queries:
# Handle queries where variables are missing entirely from our data
if query_numerator not in adjacency_list or query_denominator not in adjacency_list:
final_answers.append(-1.0)
continue
visited_set = set()
answer = explore_paths(query_numerator, query_denominator, 1.0, visited_set)
final_answers.append(answer)
return final_answersThe optimal strategy is to view the problem like a map of connected cities, where each relationship between two quantities acts as a bridge with a specific conversion multiplier. To find the ratio between any two quantities, we simply trace a path of bridges connecting them, multiplying the conversion values along the way.
Here's how the algorithm would work step-by-step:
from collections import defaultdict, deque
def calc_equation(equations, values, queries):
adjacency_graph = defaultdict(dict)
for (numerator, denominator), division_value in zip(equations, values):
adjacency_graph[numerator][denominator] = division_value
adjacency_graph[denominator][numerator] = 1.0 / division_value
def search_conversion_path(start_point, target_point):
# Unknown quantities cannot form a valid path, so we fail early.
if start_point not in adjacency_graph or target_point not in adjacency_graph:
return -1.0
# A quantity divided by itself is always one without needing traversal.
if start_point == target_point:
return 1.0
exploration_queue = deque([(start_point, 1.0)])
visited_nodes = {start_point}
while exploration_queue:
current_node, accumulated_factor = exploration_queue.popleft()
if current_node == target_point:
return accumulated_factor
for neighbor_node, conversion_rate in adjacency_graph[current_node].items():
if neighbor_node not in visited_nodes:
visited_nodes.add(neighbor_node)
next_factor = accumulated_factor * conversion_rate
exploration_queue.append((neighbor_node, next_factor))
# Exhausting all connected paths without finding the target means no valid ratio exists.
return -1.0
final_results = []
for start_variable, target_variable in queries:
conversion_result = search_conversion_path(start_variable, target_variable)
final_results.append(conversion_result)
return final_results| Case | How to Handle |
|---|---|
| Variables in queries do not exist in the given equations | Return -1.0 for these queries because no relationship path can be established in the graph. |
| Division by zero where a denominator value is zero | The problem constraints typically guarantee valid positive values, but zero-weight edges should be handled to avoid undefined division results. |
| A variable is divided by itself, such as a query like a / a | Return 1.0 if the variable exists in our graph, or -1.0 if it is completely unknown. |
| Graph contains cycles due to redundant or mutually dependent equations | Use a visited set during graph traversal (DFS or BFS) to prevent infinite loops. |
| Disconnected components in the equation graph | The traversal will fail to reach the target node and correctly return -1.0 for queries between unconnected variables. |
| Large number of equations leading to deep recursion stacks | Use an iterative BFS or union-find algorithm instead of recursive DFS to avoid stack overflow errors. |
| Floating point precision inaccuracies accumulating over long paths | While standard double precision is usually sufficient, using relative tolerance comparisons can help mitigate precision drift. |
| Single equation provided with a query asking for one of its variables | The graph builds correctly with two nodes and a directed weighted edge, allowing direct lookup of the ratio. |