Skip to content

Commit afd9b2b

Browse files
authored
Update satisfiability-of-equality-equations.cpp
1 parent f362eaf commit afd9b2b

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

C++/satisfiability-of-equality-equations.cpp

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,60 @@
22
// Space: O(1)
33

44
class Solution {
5+
public:
6+
bool equationsPossible(vector<string>& equations) {
7+
UnionFind union_find(26);
8+
for (const auto& eqn : equations) {
9+
int x = eqn[0] - 'a';
10+
int y = eqn[3] - 'a';
11+
if (eqn[1] == '=') {
12+
union_find.union_set(x, y);
13+
}
14+
}
15+
for (const auto& eqn : equations) {
16+
int x = eqn[0] - 'a';
17+
int y = eqn[3] - 'a';
18+
if (eqn[1] == '!') {
19+
if (union_find.find_set(x) == union_find.find_set(y)) {
20+
return false;
21+
}
22+
}
23+
}
24+
return true;
25+
}
26+
27+
28+
private:
29+
class UnionFind {
30+
public:
31+
UnionFind(const int n) : set_(n) {
32+
iota(set_.begin(), set_.end(), 0);
33+
}
34+
35+
int find_set(const int x) {
36+
if (set_[x] != x) {
37+
set_[x] = find_set(set_[x]); // Path compression.
38+
}
39+
return set_[x];
40+
}
41+
42+
bool union_set(const int x, const int y) {
43+
int x_root = find_set(x), y_root = find_set(y);
44+
if (x_root == y_root) {
45+
return false;
46+
}
47+
set_[min(x_root, y_root)] = max(x_root, y_root);
48+
return true;
49+
}
50+
51+
private:
52+
vector<int> set_;
53+
};
54+
};
55+
56+
// Time: O(n)
57+
// Space: O(1)
58+
class Solution2 {
559
public:
660
bool equationsPossible(vector<string>& equations) {
761
vector<vector<int>> graph(26);

0 commit comments

Comments
 (0)