Skip to content

Commit 58a9ab1

Browse files
committed
Runtime: 1 ms (Top 98.0%) | Memory: 40.98 MB (Top 47.4%)
1 parent 5d3470a commit 58a9ab1

File tree

1 file changed

+43
-55
lines changed

1 file changed

+43
-55
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,65 +1,53 @@
1+
// Runtime: 1 ms (Top 98.0%) | Memory: 40.98 MB (Top 47.4%)
2+
13
class Solution {
2-
private class UF{
3-
int count;
4-
int[] parent;
5-
6-
public UF(int n){
7-
count = n;
8-
parent = new int[n];
9-
for(int i = 0; i < n; i++){
10-
parent[i] = i;
11-
}
12-
}
13-
14-
public int find(int x){
15-
if(parent[x] != x){
16-
parent[x] = find(parent[x]);
17-
}
18-
return parent[x];
19-
}
20-
21-
public void union(int a, int b){
22-
int rootA = find(a);
23-
int rootB = find(b);
24-
if(rootA == rootB){
25-
return;
26-
}
27-
parent[rootA] = rootB;
28-
count --;
29-
}
30-
31-
public boolean connected(int a, int b){
32-
int rootA = find(a);
33-
int rootB = find(b);
34-
if(rootA == rootB){
35-
return true;
36-
}else{
37-
return false;
38-
}
39-
}
4+
static int par[];
5+
6+
public static int findPar(int u) {
7+
return par[u] == u ? u : (par[u] = findPar(par[u]));
408
}
9+
4110
public boolean equationsPossible(String[] equations) {
42-
UF uf = new UF(26);
43-
int count = 0;
44-
for(String s : equations){
45-
if(s.charAt(1) == '='){
46-
uf.union(s.charAt(0) - 'a', s.charAt(3) - 'a');
47-
}else{
48-
equations[count] = s;
49-
count++;
50-
}
11+
par = new int[26];
12+
for (int i = 0; i < 26; i++) {
13+
par[i] = i;
5114
}
52-
for(String s : equations){
53-
count --;
54-
if(count < 0){
55-
break;
56-
}
57-
if(s.charAt(1) == '!'){
58-
if(uf.connected(s.charAt(0) - 'a', s.charAt(3) - 'a')){
15+
16+
/*First perform all the merging operation*/
17+
for (String s : equations) {
18+
int c1 = s.charAt(0) - 'a';
19+
int c2 = s.charAt(3) - 'a';
20+
char sign = s.charAt(1);
21+
22+
int p1 = findPar(c1);
23+
int p2 = findPar(c2);
24+
25+
if (sign == '=') {
26+
if (p1 != p2) {
27+
if (p1 < p2) {
28+
par[p2] = p1;
29+
} else {
30+
par[p1] = p2;
31+
}
32+
}
33+
}
34+
}
35+
36+
/*Now traverse on the whole string and search for any != operation and check if there parents are same*/
37+
for (String s : equations) {
38+
int c1 = s.charAt(0) - 'a';
39+
int c2 = s.charAt(3) - 'a';
40+
char sign = s.charAt(1);
41+
42+
int p1 = findPar(c1);
43+
int p2 = findPar(c2);
44+
45+
if (sign == '!') {
46+
if (p1 == p2) {
5947
return false;
6048
}
6149
}
6250
}
6351
return true;
6452
}
65-
}
53+
}

0 commit comments

Comments
 (0)