You are given an array of strings equations that represent relationships between variables where each string equations[i] is of length 4 and takes one of two different forms: "xi==yi" or "xi!=yi".Here, xi and yi are lowercase letters (not necessarily different) that represent one-letter variable names.
Return trueif it is possible to assign integers to variable names so as to satisfy all the given equations, orfalseotherwise.
Input: equations =["a==b","b!=a"]Output: falseExplanation: If we assign say, a =1 and b =1, then the first equation is satisfied, but not the second.There is no way to assign the variables to satisfy both equations.
Example 2:
1
2
3
Input: equations =["b==a","a==b"]Output: trueExplanation: We could assign a =1 and b =1 to satisfy both equations.
Considering the example ["a==b", "b!=c", "c==a"], a and b belong to the same set. However, b and c should not be in the same set. Therefore, when trying to place c and a in the same set, it causes a contradiction since b and c cannot coexist in the same set. We can address this using code similar to Disjoint Set - Weighted Union Implementation.
classSolution {
int[] parent =newint[26];
int[] size =newint[26];
publicbooleanequationsPossible(String[] equations) {
for (int i = 0; i<26; i++) {
size[i]= 1;
parent[i]= i;
}
for (String s: equations) {
if (s.charAt(1) =='=') {
int a = s.charAt(0) -'a';
int b = s.charAt(3) -'a';
union(a, b);
}
}
for (String s: equations) {
if (s.charAt(1) =='!') {
int a = s.charAt(0) -'a';
int b = s.charAt(3) -'a';
if (isConnected(a, b)) {
returnfalse;
}
}
}
returntrue;
}
publicvoidunion(int a, int b) {
int roota = find(a);
int rootb = find(b);
if (roota == rootb) {
return;
}
if (size[roota]>= size[rootb]) {
parent[rootb]= roota;
size[roota]+= size[rootb];
} else {
parent[roota]= rootb;
size[rootb]+= size[roota];
}
}
publicintfind(int a) {
while (parent[a]!= a) {
a = parent[a];
}
return a;
}
publicbooleanisConnected(int a, int b) {
int roota = find(a);
int rootb = find(b);
if (roota == rootb) {
returntrue;
}
returnfalse;
}
}