990. Satisfiability of Equality Equations
Problem
Each equation is a 4-character string "x==y" or "x!=y" over single lowercase-letter variables. Decide whether integers can be assigned to the variables so that every equation holds.
Example: ["a==b","b!=a"] → false; ["b==a","a==b"] → true
First union all a==b; then every a!=b must have different roots.
Complexity: O(n · α(26)).
class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
parent = list(range(26))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for e in equations:
if e[1] == "=":
parent[find(ord(e[0]) - 97)] = find(ord(e[3]) - 97)
return all(find(ord(e[0]) - 97) != find(ord(e[3]) - 97) for e in equations if e[1] == "!")
assert Solution().equationsPossible(["a==b", "b!=a"]) is False
assert Solution().equationsPossible(["b==a", "a==b"]) is True
assert Solution().equationsPossible(["a==b", "b==c", "a==c"]) is True
class Solution {
private final int[] p = new int[26];
private int find(int x) {
while (p[x] != x) { p[x] = p[p[x]]; x = p[x]; }
return x;
}
public boolean equationsPossible(String[] equations) {
for (int i = 0; i < 26; i++) p[i] = i;
for (String e : equations) if (e.charAt(1) == '=') p[find(e.charAt(0) - 'a')] = find(e.charAt(3) - 'a');
for (String e : equations) if (e.charAt(1) == '!' && find(e.charAt(0) - 'a') == find(e.charAt(3) - 'a')) return false;
return true;
}
}
func equationsPossible(equations []string) bool {
var parent [26]int
for i := range parent {
parent[i] = i
}
find := func(x int) int {
for parent[x] != x {
parent[x] = parent[parent[x]]
x = parent[x]
}
return x
}
for _, e := range equations { // union all "==" first
if e[1] == '=' {
parent[find(int(e[0]-'a'))] = find(int(e[3] - 'a'))
}
}
for _, e := range equations { // then every "!=" must span two groups
if e[1] == '!' && find(int(e[0]-'a')) == find(int(e[3]-'a')) {
return false
}
}
return true
}