Taro Logo

Evaluate Division

#10 Most AskedMedium
0 views
Topics:
GraphsStrings

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 <= 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.

Solution


Clarifying Questions

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:

  1. What should be returned for a query if one or both of the variables in the query do not exist at all in the given equations?
  2. Can we assume that the input equations are always consistent (i.e., no contradictions like A / B = 2 and B / C = 3 while A / C = 5), or could invalid/contradictory input be provided?
  3. What should the result be if a query asks to divide a variable by itself, but that variable was never present in any of the given equations?
  4. Can we encounter division by zero in the input equations (e.g., A / B where B = 0), or will all denominator values be non-zero real numbers?
  5. Is the graph formed by the equations guaranteed to be connected, or could we have multiple disconnected components and queries that span across them?

Brute Force Solution

Approach

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:

  1. Begin at the starting item specified in your question.
  2. Look at every direct connection leading away from your current item to see if your target item is right next door.
  3. If your target is not there, pick one of the connected items and follow that path as far as you can.
  4. Multiply the numbers together along your chosen path step by step as you move forward.
  5. If you hit a dead end or wander in a circle without reaching the target, completely erase your progress, back up to the start, and try an entirely different path.
  6. Exhaust every possible combination of paths and detours until you either successfully trace a route to the target item or run out of paths completely.
  7. If you manage to reach the target, report the final multiplied number; otherwise, admit defeat and state that the connection cannot be made.

Code Implementation

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_answers

Big(O) Analysis

Time Complexity
O(V + E) – In this graph traversal approach, V represents the number of unique variables (nodes) and E represents the number of given equation pairs (directed edges). During each query, the algorithm may need to explore every connected node and edge in the worst-case scenario. Summing the traversal costs for all queries leads to approximately Q * (V + E) operations, where Q is the number of queries, which simplifies to O(Q * (V + E)) or O(V + E) per query.
Space Complexity
O(V + E) – The auxiliary space is driven by the graph representation stored in a hash map, where V is the number of unique variables and E is the number of equations, holding all directed connections and multipliers. Additionally, the recursion stack and the visited set used to track locations during path exploration can grow up to a depth of V in the worst-case scenario. Therefore, the total extra memory scales linearly with the number of unique items and their relationships in the graph.

Optimal Solution

Approach

The 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:

  1. Gather all the given conversion facts and picture them as a web of connected points, where each point represents a quantity and each bridge represents how many times one quantity fits into another.
  2. When asked to find the relationship between a starting point and a target point, check if both points exist in our web of facts.
  3. If either point is completely unknown, we immediately know the answer is impossible, so we stop and return a failure signal.
  4. If the starting point and target point are actually the exact same thing, the ratio is simply one, because a quantity always divides into itself once.
  5. Otherwise, start at the starting point and walk along the bridges to explore all reachable neighboring points, keeping track of the cumulative multiplication factor as you travel.
  6. Continue exploring step by step until you successfully reach the target point, and the accumulated multiplication factor at that moment is your final answer.
  7. If you explore every possible connected path and still cannot reach the target point, it means no valid bridge network exists between them, so return a failure signal.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(V + Q * (V + E)) – Building the graph takes time proportional to the number of equations and variables, resulting in V vertices and E directed edges. For each of the Q queries, we may need to traverse the entire connected component using graph exploration algorithms like Breadth-First Search or Depth-First Search, which visits every vertex and edge in the worst case. This leads to approximately Q * (V + E) operations for all queries combined, which simplifies to O(V + Q * (V + E)).
Space Complexity
O(V + E) – The extra space is driven by the graph adjacency list and the visited tracking structures used during the traversal. If we let V be the total number of unique variables and E be the number of given division equations, the hash map stores up to V nodes and 2E directed edges. Additionally, the visited set and the recursion stack or queue during the graph search each consume space proportional to the number of unique variables V in the worst-case scenario. Combining these structures yields a total auxiliary space complexity of O(V + E).

Edge Cases

Variables in queries do not exist in the given equations
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Use a visited set during graph traversal (DFS or BFS) to prevent infinite loops.
Disconnected components in the equation graph
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
The graph builds correctly with two nodes and a directed weighted edge, allowing direct lookup of the ratio.
0/11 completed