#990
Satisfiability of Equality Equations
MediumArrayStringUnion-FindGraph TheoryUnion-FindGraph Theory
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses the Union-Find data structure to group variables that are equal and then checks for contradictions with the '!=' equations. This is efficient and avoids the combinatorial explosion of the brute force method.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a Union-Find structure to manage the connected components of equal variables.
- 2Step 2: Process all '==' equations to union the variables.
- 3Step 3: For each '!=' equation, check if the two variables are in the same component; if they are, return false.
- 4Step 4: If no contradictions are found, return true.
solution.py25 lines
1# Full working Python code
2class UnionFind:
3 def __init__(self, size):
4 self.parent = list(range(size))
5
6 def find(self, x):
7 if self.parent[x] != x:
8 self.parent[x] = self.find(self.parent[x])
9 return self.parent[x]
10
11 def union(self, x, y):
12 rootX = self.find(x)
13 rootY = self.find(y)
14 if rootX != rootY:
15 self.parent[rootY] = rootX
16
17def equationsPossible(equations):
18 uf = UnionFind(26)
19 for eq in equations:
20 if eq[1] == '=':
21 uf.union(ord(eq[0]) - ord('a'), ord(eq[3]) - ord('a'))
22 for eq in equations:
23 if eq[1] == '!' and uf.find(ord(eq[0]) - ord('a')) == uf.find(ord(eq[3]) - ord('a')):
24 return False
25 return Trueℹ
Complexity note: The time complexity is O(n) because we make a constant number of operations for each equation, and the Union-Find operations are nearly constant time due to path compression.
- 1Union-Find is a powerful tool for managing connected components.
- 2Understanding the difference between equality and inequality is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.