Check for Contradictions in Equations Problem
Description
LeetCode Problem 2307.
You are given a 2D array of strings equations and an array of real numbers values, where equations[i] = [A_i, B_i] and values[i] means that A_i / B_i = values[i].
Determine if there exists a contradiction in the equations. Return true if there is a contradiction, or false otherwise.
Note:
- When checking if two numbers are equal, check that their absolute difference is less than
10^(-5). - The testcases are generated such that there are no cases targeting precision, i.e. using
doubleis enough to solve the problem.
Example 1:
Input: equations = [["a","b"],["b","c"],["a","c"]], values = [3,0.5,1.5]
Output: false
Explanation:
The given equations are: a / b = 3, b / c = 0.5, a / c = 1.5
There are no contradictions in the equations. One possible assignment to satisfy all equations is:
a = 3, b = 1 and c = 2.
Example 2:
Input: equations = [["le","et"],["le","code"],["code","et"]], values = [2,5,0.5]
Output: true
Explanation:
The given equations are: le / et = 2, le / code = 5, code / et = 0.5
Based on the first two equations, we get code / et = 0.4.
Since the third equation is code / et = 0.5, we get a contradiction.
Constraints:
1 <= equations.length <= 100equations[i].length == 21 <= A_i.length, B_i.length <= 5A_i,B_iconsist of lowercase English letters.equations.length == values.length0.0 < values[i] <= 10.0values[i]has a maximum of 2 decimal places.
Solution
Approach: Weighted Union-Find
Number the variables and keep a union-find where each node stores its ratio to its root. For each equation a / b = v, if a and b are in different sets, merge them and set the ratio accordingly. If they are already in the same set, compare the ratio implied by the structure with v; a mismatch (beyond 1e-5) means a contradiction, so return true. If no equation conflicts, return false.
Complexity: About O(n log n) time (near O(n) with path compression), O(n) space, where n is the number of equations.
from collections import defaultdict
class Solution:
def checkContradictions(
self, equations: List[List[str]], values: List[float]
) -> bool:
def find(x: int) -> int:
if p[x] != x:
root = find(p[x])
w[x] *= w[p[x]]
p[x] = root
return p[x]
d = defaultdict(int)
n = 0
for e in equations:
for s in e:
if s not in d:
d[s] = n
n += 1
p = list(range(n))
w = [1.0] * n
eps = 1e-5
for (a, b), v in zip(equations, values):
a, b = d[a], d[b]
pa, pb = find(a), find(b)
if pa != pb:
p[pb] = pa
w[pb] = v * w[a] / w[b]
elif abs(v * w[a] - w[b]) >= eps:
return True
return False