Evaluate Division
Understand how to apply Union Find techniques to solve Evaluate Division problems by determining variable ratios from given equations and values. Learn to address queries effectively and recognize impossible cases.
We'll cover the following...
Statement
We are given three arrays:
equations: Here, eachequations[i]represents a pair of variables[a[i], b[i]], where eacha[i]orb[i]is a string that represents a single variable.values: This array contains real numbers that are the result values when the first variable inequations[i]is divided by the second. For example, ifequations[i] = ["m", "n"]andvalues[i] = 2.0, it means thatm / n = 2.0.queries: Here, eachqueries[i]represents a pair of variables[c[i], d[i]], where eachc[i]ord[i]is a string that represents a single variable. The answer to each query must be calculated asc[i] / d[i].
Given these arrays, find the result of each queries[i] by dividing the first variable with the second. To answer all the queries correctly, use the given equations and values. If it's impossible to determine the answer to any query based on the given equations and values, return
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.
Constraints:
equations.lengthequations[i].lengtha[i].length,b[i].lengthvalues.lengthequations.lengthvalues[i]queries.lengthqueries[i].lengthc[j].length,d[j].lengtha[i], b[i], c[j], d[j]consist of lower case English letters and digits.
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Evaluate Division
What is the correct output if the following values are given as input?
equations = [[“a”, “b”]]
values = [1.5]
queries = [[“a”, “b”], [“c”, “b”], [“x”, “x”]]
[1.5, 1.0, -1.0]
[1.5, -1.0, -1.0]
[1.5, -1.0, 1.0]
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Note: As an additional challenge, we have intentionally hidden the solution to this puzzle.
Try it yourself
Implement your solution in the following coding playground.
We have left the solution to this challenge as an exercise for you. The optimal solution to this problem runs in O((m+n).logn) time and takes O(n) space. You may try to translate the logic of the solved puzzle into a coded solution.
"""⬅️ We have provided a union_find.py file under the "Files" tabof this widget. You can use this file to build your solution."""from union_find import UnionFinddef evaluate_equations(equations, values, queries):# Replace this placeholder return statement with your codereturn []