Leetcode 399: Evaluate Division

grid47
grid47
Exploring patterns and algorithms
Sep 28, 2024 7 min read

A set of equations forming a division problem, with the answer softly glowing as it is calculated.
Solution to LeetCode 399: Evaluate Division Problem

You are given a list of equations and their corresponding values, where each equation represents a division between two variables. Your task is to determine the result of several queries asking for the division result of two given variables.
Problem
Approach
Steps
Complexity
Input: You are given two lists: `equations` representing division relations and `values` representing the results of those divisions. You are also given a list of `queries` that you need to evaluate.
Example: Input: equations = [['a', 'b'], ['b', 'c']], values = [2.0, 3.0], queries = [['a', 'c'], ['b', 'a']]
Constraints:
• 1 <= equations.length <= 20
• 1 <= queries.length <= 20
• Each equation contains two strings with lengths from 1 to 5.
Output: For each query, return the result of the division if it can be determined, otherwise return -1.0.
Example: Output: [6.0, 0.5, -1.0, 1.0, -1.0]
Constraints:
• The division is guaranteed to be valid for each equation.
• Queries asking for divisions between undefined variables must return -1.0.
Goal: Use depth-first search (DFS) to explore possible paths in the graph and compute the result of each query.
Steps:
• Construct a graph where each variable is a node, and each equation provides an edge with a weight representing the division result.
• For each query, use DFS to explore the graph from the starting node (variable) to the target node and compute the division result along the path.
Goal: Ensure that there are no contradictions in the input equations and that division by zero does not occur.
Steps:
• The variables in queries must be part of the equations provided.
Assumptions:
• All equations are valid and there are no contradictions.
• Evaluating queries will not result in division by zero.
Input: For the equations [['a', 'b'], ['b', 'c']] and values [2.0, 3.0], the query ['a', 'c'] will return 6.0 because a / b = 2 and b / c = 3, so a / c = 2 * 3 = 6.
Explanation: We first find the direct relations between variables and then use those relations to compute the result for each query.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus