-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathequationsPossible.ts
54 lines (42 loc) · 1.44 KB
/
equationsPossible.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// ref: classes/UnionFind
import { lowercaseCharToArrayIndex } from 'utils/char/lowercaseCharToArrayIndex'
// <Union Find>
// Time: O(nα(m)), α() is the inverse Ackermann function
// Space: O(1)
// n for the number of equations
// m for the number of variables
function find(parents: number[], x: number): number {
while (parents[x] !== x) {
parents[x] = parents[parents[x]] // path compression
x = parents[x]
}
return x
}
function union(parents: number[], x: number, y: number): void {
parents[find(parents, x)] = find(parents, y)
}
function equationsPossible(equations: string[]): boolean {
// edge cases
if (!equations.length) {
return false
}
const parents = Array.from({ length: 26 }, (_, i) => i)
for (const equation of equations) {
if (equation.charAt(1) === '=') {
const indexX = lowercaseCharToArrayIndex(equation.charAt(0))
const indexY = lowercaseCharToArrayIndex(equation.charAt(3))
union(parents, indexX, indexY)
}
}
for (const equation of equations) {
if (equation.charAt(1) === '!') {
const indexX = lowercaseCharToArrayIndex(equation.charAt(0))
const indexY = lowercaseCharToArrayIndex(equation.charAt(3))
if (find(parents, indexX) === find(parents, indexY)) {
return false
}
}
}
return true
}
export { equationsPossible }