Problem Description
Given a set of equations of the form A / B = k, where each equation relates two variables with a real number, determine if there is any contradiction among the equations. A contradiction occurs if the value computed for an equation via other relationships differs from the provided ratio beyond a tolerance (absolute difference < 10^-5).
Key Insights
- Model the problem as a graph where each variable is a node.
- Each equation creates an edge connecting two nodes with an associated weight.
- Use Depth-First Search (DFS) to propagate and assign a relative value (ratio) to each variable in a connected component.
- During DFS, if a variable is revisited, compare the computed ratio with the stored ratio to check for consistency.
- A difference greater than 10^-5 between the computed and stored ratios indicates a contradiction.
Space and Time Complexity
Time Complexity: O(N + M), where N is the number of variables (nodes) and M is the number of equations (edges), since each node and edge is processed during DFS. Space Complexity: O(N + M), for storing the graph and recursion stack (or Union-Find structures).
Solution
We solve the problem by constructing an adjacency list to represent the graph, where each node (variable) connects with others by storing the corresponding division factors. We then use DFS to assign each variable a relative value (or ratio) starting from an arbitrary value of 1 for each connected component. As we propagate these ratios, if we revisit a node and the current computed ratio deviates from its stored value beyond a tolerance (10^-5), we have detected a contradiction. This method ensures that any inconsistency among provided equations is identified.